如何将所需的Json List对象以及剩余的Json属性提取到模型类中



//这是我目前正在使用的Json。。

{
"groups": null,
"data": [{
"type": 123,
"name": "Name123"
},
{
"type": 567,
"name": "SecondName"
}
],
"total": 2
}

//这是我想要反序列化最后一个对象"的模型类;数据";包括";组";以及总

public class JsonModel
{
public class Data
{
public int type { get; set; }
public string name { get; set; }
}

public object groups { get; set; }
public Date[] data { get; set; }
public int total { get; set; }
}
//FYI using RestSharp to perform the request 
response = HttpGet("Url")
parsedResponse =   JToken.Parse(response.content);
JsonModel.Date expectedData = JsonConvert.DeserializeObject<JsonModel.Date> 
(parsedResponse["data"].Last.ToString());

//After deserialzing I only get the type and name.. how to also get the groups and total here in my JsonModel to correctly map it.. I understand I am deserializing to JsonModel.Date thats why.. but how can I include the total and groups property..

我使用在线工具来转换json。结果如下:

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
public class Datum    {
public int type { get; set; } 
public string name { get; set; } 
}
public class Root    {
public object groups { get; set; } 
public List<Datum> data { get; set; } 
public int total { get; set; } 
}

您需要继续按属性进行解析,然后手动创建JsonModel的新实例:

var result = new JsonModel
{
data = new [] {parsedResponse["data"].Last.ToObject<JsonModel.Date>()},
groups = parsedResponse["groups"].ToObject<object>(),
total = parsedResponse["total"].Value<int>()
};

或者,您可以对其进行反序列化并重新分配data属性:

var result = JsonConvert.DeserializeObject<JsonModel>(response.content);
result.data = new[] {result.data.Last()};

相关内容

  • 没有找到相关文章

最新更新