2017-10-15 83 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