我试图使用NewtonSoft json 4.5解析以下json字符串:
public class Parent
{
public string Name { get; set; }
[JsonProperty(PropertyName = "Children")]
public List<Child> Childs { get; set; }
}
public class Child {
public string Name { get; set; }
[JsonProperty(PropertyName = "Grandchildren")]
public List<GrandChild> GrandChilds { get; set; }
}
public class GrandChild {
[JsonProperty(PropertyName = "")]
public string Name { get; set; }
}
我将序列化为json的对象看起来像这样:
async function asyncFunc() {
try {
await somePromise();
} catch (error) {
throw new Error(error);
}
}
我已尝试将属性名称设置为空,但它无法解决问题。
答案 0 :(得分:1)
您应该将List<GrandChild>
替换为List<string>
,或者为JsonConverter
添加自定义GrandChild
。
[JsonConverter(typeof(GrandChildConverter))]
public class GrandChild
{
public string Name { get; set; }
}
public class GrandChildConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(GrandChild);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((GrandChild)value).Name);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return new GrandChild { Name = reader.Value.ToString() };
}
}