我正在使用System.Runtime.Serialization.Json库
这不起作用
public class Detections
{
[DataContract]
public class RootObject
{
[DataMember(Name = "data")]
public DataObject Data { get; set; }
}
[DataContract]
public class DataObject
{
[DataMember(Name = "detections")]
public List<Detection> Detections { get; set; }
}
[DataContract]
public class Detection
{
[DataMember(Name = "language")]
public string Language { get; set; }
[DataMember(Name = "isReliable")]
public string IsReliable { get; set; }
[DataMember(Name = "confidence")]
public string Confidence { get; set; }
}
}
那我应该如何解析这个
{
"data": {
"detections": [
[
{
"language": "tr",
"isReliable": false,
"confidence": 0.086520955
}
]
]
}
}
答案 0 :(得分:5)
问题出现有两个原因。
1)您需要从Detections类中删除嵌套类。
2)JSON包含检测成员的多维数组,我认为它必须是单个数据。
我已经测试了下面详细说明的代码,它运行正常。
//Classes
[DataContract]
public class RootObject
{
[DataMember(Name = "data")]
public DataObject Data { get; set; }
}
[DataContract]
public class DataObject
{
[DataMember(Name = "detections")]
public List<Detection> Detections { get; set; }
}
[DataContract]
public class Detection
{
[DataMember(Name = "language")]
public string Language { get; set; }
[DataMember(Name = "isReliable")]
public string IsReliable { get; set; }
[DataMember(Name = "confidence")]
public string Confidence { get; set; }
}
//Code to deserialize
var serializer = new DataContractJsonSerializer(typeof(RootObject));
var json = "{\"data\": {\"detections\": [{\"language\": \"tr\",\"isReliable\": false,\"confidence\": 0.086520955}]}}";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
var rootObject = serializer.ReadObject(stream);
stream.Close();
我希望这可以帮到你。
答案 1 :(得分:0)
除了Detections
是集合的集合之外,一切都是正确的。我不知道为什么会这样,但它对我有用。
[DataContract]
public class DataObject
{
[DataMember(Name = "detections")]
public List<List<Detection>> Detections { get; set; }
}
答案 2 :(得分:0)
在你的json中,“Detection”是一个列表列表。请注意,jdavies的答案不承认这一点。
[DataContract]
public class DataObject
{
[DataMember(Name = "detections")]
public List<List<Detection>> Detections { get; set; }
}