这是我的结果JSON
{
"value": [
{
"name": "AAA",
"Results": [
"{\"name\":\"Maths\",\"type\":\"Person\",\"subType\":null}",
"{\"name\":\"English\",\"type\":\"Person\",\"subType\":null}"
]
},
{
"name": "BBB",
"Results": [
"{\"name\":\"Bio\",\"type\":\"Person\",\"subType\":null}",
"{\"name\":\"Physics\",\"type\":\"Person\",\"subType\":null}"
]
}
]
}
这是我的价值模型
public class ValueModel
{
public string name { get; set; }
public List<string> Results { get; set; }
}
主要型号:
public class MainModel
{
public List<ValueModel> value {get;set;}
}
Result值始终以JSON字符串格式出现,我无法更改。
现在我已经为结果设置了一个单独的类,如下所示:
public class ResultModel
{
public string name {get;set;}
public string type {get;set;}
public string subType {get;set;}
}
我想要的就是将结果Jsonstring转换为ResultModel
到目前为止,我尝试像在getter setter本身中一样,但是不起作用
public class ValueModel
{
public string name { get; set; }
public List<string> Results { get; set; }
[JsonIgnore]
public List<ResultModel> ProperResults
{
get
{
string json = JsonConvert.SerializeObject(Results , Formatting.Indented);
return JsonConvert.DeserializeObject<List<ResultModel>>(json);
}
}
}
更新1
@Aleks解决方案运行完美,但是问题是我的结果JSON中有另一个@odata.count
这样的Json属性
{ "@odata.count": 2
"value": [
{
"name": "AAA",
"Results": [
"{\"name\":\"Maths\",\"type\":\"Person\",\"subType\":null}",
"{\"name\":\"English\",\"type\":\"Person\",\"subType\":null}"
]
},
{
"name": "BBB",
"Results": [
"{\"name\":\"Bio\",\"type\":\"Person\",\"subType\":null}",
"{\"name\":\"Physics\",\"type\":\"Person\",\"subType\":null}"
]
}
]
}
所以我试图像
那样修改模板var template = new { odataCount=0,value = new[] {new {name = "", Results = new string[0]}}};
bcos无法正常工作,它无法映射@odata.count
元素
答案 0 :(得分:1)
您的输入包含嵌套的Json,因此您应该通过几步反序列化它
您可以像定义ValueModel
public class ValueModel
{
public string name { get; set; }
public List<ResultModel> Results { get; set; }
}
现在将输入反序列化为临时匿名对象:
var input = "{\r\n \"value\": [\r\n {\r\n \"name\": \"AAA\",\r\n \"Results\": [\r\n \"{\\\"name\\\":\\\"Maths\\\",\\\"type\\\":\\\"Person\\\",\\\"subType\\\":null}\",\r\n \"{\\\"name\\\":\\\"English\\\",\\\"type\\\":\\\"Person\\\",\\\"subType\\\":null}\"\r\n ]\r\n },\r\n {\r\n \"name\": \"BBB\",\r\n \"Results\": [\r\n \"{\\\"name\\\":\\\"Bio\\\",\\\"type\\\":\\\"Person\\\",\\\"subType\\\":null}\",\r\n \"{\\\"name\\\":\\\"Physics\\\",\\\"type\\\":\\\"Person\\\",\\\"subType\\\":null}\"\r\n ]\r\n }\r\n ]\r\n}";
var template = new {value = new[] {new {name = "", Results = new string[0]}}};
var mainModel = JsonConvert.DeserializeAnonymousType(input, template);
这时您可以获得预期的结果
var result = new MainModel
{
value = mainModel.value.Select(x => new ValueModel
{
name = x.name,
Results = x.Results.Select(JsonConvert.DeserializeObject<ResultModel>).ToList()
}).ToList()
};
@odata.count
,但是您可以为此使用JObject
:
var jObject = JObject.Parse(input);
(int) jObject["@odata.count"]; // == 2