Reputation: 3133
I am getting 'Error converting value' when I try to use deserilizeobject. My client sometimes sends data with quotes and special characters in it. It works when they try to serialize it. But it doesn't work when I try to deserilize it. I tried with escapehtml but still I have the same issue. It looks like 'SerializeObject' is not throwing error message that means it's valid JSON. Please let me know how to solve this issue.
string json2 = @"{
'RootObject1':{
't_date': '03-JAN-2016',
't_summary': 'test """"""""""""'
}
}";
var json3 = JsonConvert.SerializeObject(json2, Newtonsoft.Json.Formatting.None, new Newtonsoft.Json.JsonSerializerSettings{ StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml });
var myJsonObject = JsonConvert.DeserializeObject<RootObject1>(json3);
class RootObject1
{
public string t_date { get; set; }
public string t_summary { get; set; }
}
Upvotes: 0
Views: 4495
Reputation: 7706
This is not the correct way how you should use JsonConvert.Serialize
and Deserialize
.
At the beginning you should Serialize the object to string and then Deserialize back from string to object. Here is example of that:
RootObject1 ro = new RootObject1();
ro.t_date = "03-JAN-2016";
ro.t_summary = @"test """"""""""""";
var json3 = JsonConvert.SerializeObject(ro, typeof(RootObject1), Newtonsoft.Json.Formatting.None, new Newtonsoft.Json.JsonSerializerSettings { StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml });
var myJsonObject = JsonConvert.DeserializeObject<RootObject1>(json3);
Console.WriteLine(myJsonObject.t_date + "\t" + myJsonObject.t_summary);
When you are trying to Serialize string then it will be Deserialze to string also. And it has no meaning at some point to do that.
Also if you want to get the object from JSON string you should do Deserealization and your JSON string is not valid. Here is example how you can achieve that:
string json2 = @"{
't_date': '03-JAN-2016',
't_summary': 'test """"""""""""'
}";
var obj = JsonConvert.DeserializeObject<RootObject1>(json2);
Console.WriteLine(obj.t_date + "\t" + obj.t_summary);
Upvotes: 1