由于您的属性很复杂,您需要编写自己的反序列化逻辑。
这是我的,但这只是一个例子:
- First of all, your text property seems to be
在这种情况下,我将选择“始终列出”结果,具有单个值的情况将只是一个包含一个条目的列表。
public List<TextProperty> text;
- The value can also be
- 单个字符串值
- 具有字符串值和元数据(文本类型)的对象
再说一遍,如果它只是字符串,我会选择没有类型的“始终对象”
public class TextProperty
{
public string text { get; set; }
public string type { get; set; }
}
然后你必须制作自己的 Converter 来处理这个问题,你只需继承 JsonConverter 并实现逻辑
public class TextPropertyConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException(); // not covered here
}
// A value can be either single string or object
// Return a TextProperty in both cases
private TextProperty ParseValue(JToken value)
{
switch(value.Type)
{
case JTokenType.String:
return new TextProperty { text = value.ToObject<string>() };
case JTokenType.Object:
return value.ToObject<TextProperty>();
default:
return null;
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// You'll start either with a single value (we'll convert to list of one value) or an array (list of several values then)
switch(reader.TokenType)
{
case JsonToken.String:
case JsonToken.StartObject:
return new List<TextProperty> { ParseValue(JToken.Load(reader)) };
case JsonToken.StartArray:
var a = JArray.Load(reader);
var l = new List<TextProperty>();
foreach(var v in a)
l.Add(ParseValue(v));
return l;
default:
return null;
}
}
public override bool CanConvert(Type objectType) => false;
}
我认为所有情况都应该涵盖
要使用它,只需将 JsonConverter 属性添加到目标属性即可
public class JSONObject
{
public int id;
public string type;
public string date;
public string edited;
public string from;
public int from_id;
public string photo;
public int width;
public int height;
[JsonConverter(typeof(TextPropertyConverter))]
public List<TextProperty> text;
}
然后测试一下:
static void Main(string[] args)
{
string json = @"
[
{
""id"": 397910,
""type"": ""message"",
""date"": ""2018-02-21T10:27:59"",
""edited"": ""1970-01-01T01:00:00"",
""from"": ""Username"",
""from_id"": 39033284,
""text"": ""Some Text""
},
{
""id"": 397911,
""type"": ""message"",
""date"": ""2018-02-21T10:31:47"",
""edited"": ""1970-01-01T01:00:00"",
""from"": ""Username"",
""from_id"": 272964614,
""text"": [
""Some Text "",
{
""type"": ""mention"",
""text"": ""@school""
},
"" Some Text""
]
}
]";
List<JSONObject> jsonObjects = JsonConvert.DeserializeObject<List<JSONObject>>(json);
Console.Read();
}
结果如下: