2017-10-15 68 views
0

我有下面的代码:如何删除额外字符JSON字符串

ProductDto newProduct = new ProductDto() { Id = 2, Name = "Pixel xl",Price = 2000}; 

然后我序列通过下面的代码,并将其保存在数据库:

private static string ToJson(object model) 
{ 
    JsonSerializerSettings jsonWriter = new JsonSerializerSettings 
    { 
     NullValueHandling = NullValueHandling.Ignore, 
    }; 

    var type = model.GetType(); 
    Dictionary<string, string> dic = new Dictionary<string, string>(); 

    foreach (PropertyInfo item in type.GetProperties()) 
    {  
     var propName = item.Name; 

     var propValue = item.GetValue(model); 
     if (propValue == null) continue; 

     propValue = JsonConvert.SerializeObject(propValue, Formatting.Indented, jsonWriter); 

     dic.Add(propName, propValue.ToString()); 
    } 

    return JsonConvert.SerializeObject(dic); 
} 

在数据库中的结果是象下面这样:

{ “ID”: “2”, “姓名”: “\” 像素XL \ “”, “价格”: “2000”}

所以当我读到的字符串,它Desialize下面我有值名称:

\"Pixel xl\"相反:Pixel xl

我想比较那些像“这一点,但beceasue \他们不一样。

// newValue is "Pixel xl"; 
// oldValue is "\"Pixel xl\""; 

if (!Object.Equals(newValue, oldValue))// this line always return true 
{ 
    // do somethid if they are not same 
} 
+1

你的意思是它被保存在数据库中'\“'值? –

+0

@JericCruz我的意思是我焕它featch从DB我不需要'\”'怎么一回事,因为我想将它与另一个字符串 – FullStack

+1

比较这将永远不会是真实的,因为您通过引用比较它 –

回答

0

第一:

看来你正在使用错误的比较表达式。通过使用Object.Equal,您可以看到newValueoldValue具有相同的对象。它们具有相同的“值”但不同“对象”。

MSDN

如果当前实例是引用类型,的Equals(Object)方法 试验引用相等,并以等于呼叫(Object)方法 相当于到呼叫ReferenceEquals方法。参考 相等意味着被比较的对象变量指的是同一个对象的 。

第二:

转换后的值有一个额外的双qoute \"。您可以使用.Replace("\"", "")手动删除该文件。您可能想要创建另一个比较表达式来比较您的值。 喜欢的东西:

if (newValue.Name == oldValue.Name && newValue.Id == oldValue.Id && newValue.Price == oldValue.Price) 
{ 
    Console.WriteLine("Same"); 
} 
else 
{ 
    Console.WriteLine("Not Same"); 
} 

示例代码: https://dotnetfiddle.net/mJgRsL

一个侧面说明:

您可以参考此链接价值VS参考的对象类型的差异。 https://msdn.microsoft.com/en-us/library/4d43ts61(v=vs.90).aspx