C# Parse Json - System.Runtime.Serialization.Json
本文关键字:Json Runtime Serialization System Parse | 更新日期: 2023-09-27 18:06:07
我正在使用system . runtime . serialize . 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
}
]
]
}
}
出现这个问题有两个原因。
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();
在json中"Detection"是一个列表的列表。请注意,jdavies的回答不承认这个
[DataContract]
public class DataObject
{
[DataMember(Name = "detections")]
public List<List<Detection>> Detections { get; set; }
}
一切都是正确的,除了Detections
是集合的集合。我不知道为什么会这样,但它对我很有效。
[DataContract]
public class DataObject
{
[DataMember(Name = "detections")]
public List<List<Detection>> Detections { get; set; }
}