I have a problem to deserialize a json object by using javascriptserialize method with sometimes missing attribute. I'm new in C# deserailize here is the json ouptut:
{"result": [{"id": "1", "inc_group": {"link": "XXX","value": "222"}},{"id": "2","inc_group": ""},{"id": "3","inc_group": {"link": "YYY","value": "654"}}] }
the attribute inc_group can be empty sometimes. Here is my sample script:
public class inc_group
{
public string link { get; set; }
public string value { get; set; }
}
public class Result
{
public string id { get; set; }
public inc_group inc_group { get; set; }
}
public class Root
{
public List<Result> result { get; set; }
}
using (WebResponse response = request.GetResponse())
{
Stream responseStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
{
string json = reader.ReadToEnd();
var json_Dictionary = js.Deserialize<Root>(json);
Here is the error message: extract JSON [2]: System.InvalidOperationException: Impossible to convert an object type 'System.String' to 'ScriptMain+Inc_Group'
this error appears when it deserializes the json
thanks in advance for your help
You can try with below class
public class Result
{
public string id { get; set; }
public object inc_group { get; set; }
}
public class Root
{
public List<Result> result { get; set; }
}
Root items = JsonConvert.DeserializeObject<Root>(json);
Using JavaScript Deserialization
JavaScriptSerializer js = new JavaScriptSerializer();
Root items = js.Deserialize<Root>(json);
I have tried with above class and its parsing Json and converting to C# object without any error.
Parsing data will be done as below if you are using JavaScriptSerializer
foreach (var item in items.result)
{
dynamic obj = item.inc_group;
if (obj is string)
{
string strValue = obj;
}
else
{
foreach (KeyValuePair<string, object> kvp in obj)
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
}
}
If you are using NewtonSoft JsonConvert.Deserialize method then it will be something like this.
foreach (var item in items.result)
{
dynamic obj = item.inc_group;
if (obj is string)
{
string strValue = obj;
}
else
{
string link = obj.link;
string value = obj.value;
}
}
In your Result
definition, put public inc_group? inc_group
public inc_group? inc_group
to show that that field is nullable , and thus doesn't always have to contain a value, and the deserialisation should work.
Also set set JsonSerializerOptions.IgnoreNullValues setting to true.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.