问题
This question originates from another topic which can be found at: Extract objects from JSON array to list
The thing is that I'm receiving the following JSON response, and my JSON.NET deserializer doesn't understand it, but several other JSON validators like https://jsonlint.com say that it is valid.
[
{"value":"{\"code\":\"MO\",\"description\":\"Monday\",\"isSet\":false}","nr":1}
,{"value":"{\"code\":\"TU\",\"description\":\"Tuesday\",\"isSet\":true}","nr":2}
]
In my opinion the problem here is that the value object looks like a JSON object, but actually is a string. JsonConvert.DeserializeObject keeps throwing errors until I remove the additional quotes (") and escaping chars.
So the question is, why is this response formatted like this? And how to tell the deserializer how to work with it? I'm sure that removing or replacing chars isn't the way to go.
Here is what i'm doing:
public class Value
{
public string code { get; set; }
public string description { get; set; }
public bool isSet { get; set; }
}
public class RootObject
{
public Value value { get; set; }
public int nr { get; set; }
}
var json = JsonConvert.DeserializeObject<List<RootObject>>(serviceResult);
The above doesn't work.
For the time being I have solved the issue this way. But I keep thinking that the above, with the deserializer, is more elegant.
JArray jArray = JArray.Parse(serviceResult);
List<Value> values = jArray.Select(x => JObject.Parse(x["value"].ToString()).ToObject<Value>()).ToList();
回答1:
The easiest way to do this would be to use a custom JsonConverter
, for example something like this:
public class StringToObjectConverter<T> : Newtonsoft.Json.JsonConverter
{
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
//This will only be needed if you also need to serlialise
writer.WriteRaw(JsonConvert.SerializeObject(value));
}
public override object ReadJson(JsonReader reader, Type objectType,
object existingValue, JsonSerializer serializer)
{
return JsonConvert.DeserializeObject<T>(reader.Value.ToString());
}
public override bool CanRead => true;
//We can only work with the type T, you could expand this to cope with derived types
public override bool CanConvert(Type objectType) => typeof(T) == objectType;
}
Now using these models, noting in particular the attribute on the Value
property:
public class RootObject
{
[JsonConverter(typeof(StringToObjectConverter<Value>))]
public Value value { get; set; }
public int nr { get; set; }
}
public class Value
{
public string code { get; set; }
public string description { get; set; }
public bool isSet { get; set; }
}
Now it's a simple deserialisation:
var json = "....";
var rootObjects = JsonConvert.DeserializeObject<List<RootObject>>(json);
来源:https://stackoverflow.com/questions/49771899/how-to-interpret-and-deserialize-this-json-response