I'm using newtonsoft json, and I need to serialize/deserialize this kind of json:
[
{
"value": "value1",
"field": "field1"
},
{
"value": "value2",
"field": "field2"
},
{
"value": "value3",
"field": "field3"
},
[
{
"value": "value4",
"field": "field4"
},
{
"value": "value4",
"field": "field5"
}
]
]
As you can see, I can have an object or a list of this object at the same level. I've created a class for the object but I don't know how to make the serialization process this kind of json, or if it's possible to do.
EDIT: I don't have the choice to process that json as it comes to me. So please, if you think I like this, you're wrong.
you can create a custom json converter
Result result = JsonConvert.DeserializeObject<Result>(json, new ArrayJsonConverter())
public class ArrayJsonConverter : JsonConverter<Result>
{
public override Result ReadJson(JsonReader reader, Type objectType, Result existingValue, bool hasExistingValue, JsonSerializer serializer)
{
JArray jArr = JArray.Load(reader);
var result = new Result { Items = new List<Item>(), ListItems = new List<List<Item>>() };
foreach (var item in jArr)
if (item.Type == JTokenType.Array) result.ListItems.Add(item.ToObject<List<Item>>());
else result.Items.Add(item.ToObject<Item>());
return result;
}
public override void WriteJson(JsonWriter writer, Result value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class Result
{
public List<Item> Items { get; set; }
public List<List<Item>> ListItems { get; set; }
}
public class Item
{
public string value { get; set; }
public string field { get; set; }
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments