考虑以下json:
{
"0": {
"id": "1",
"email": "someemail@test.com",
"tstamp": "2019-01-21 11:19:48",
"times": "2",
"tstamp_iso": "2019-01-21T12:19:48-05:00"
},
"1": {
"id": "2",
"email": "someotheremail@test.com",
"tstamp": "2019-01-21 11:25:48",
"times": "2",
"tstamp_iso": "2019-01-21T12:25:48-05:00"
},
"result_code": 1,
"result_message": "Success!",
"result_output": "json"
}
我正在尝试将数据转换为ac#对象,但是,我不确定如何处理数组值,因为它的名称为0
,1
而不是嵌套在一个数组中,如果有20个结果,它将持续到20。 我无法更改json数据。
我到这为止了
[JsonObject]
public class FirstObject
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "email")]
public string Email { get; set; }
[JsonProperty(PropertyName = "tstamp")]
public string TimeStamp { get; set; }
[JsonProperty(PropertyName = "times")]
public string Times { get; set; }
[JsonProperty(PropertyName = "tstamp_iso")]
public string TimeStampIso { get; set; }
}
[JsonObject]
public class SecondObject
{
public FirstObject[] FirstObjects { get; set; }
[JsonProperty(PropertyName = "result_code")]
public string ResultCode { get; set; }
[JsonProperty(PropertyName = "result_message")]
public string ResultMessage { get; set; }
[JsonProperty(PropertyName = "result_output")]
public string ResultOutput { get; set; }
}
我不了解的是如何将FirstObjects映射到0、1,... 20的结果。我希望有一种比写出20次并将名称设置为0或1更好的方法。等等...
答案 0 :(得分:1)
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace ConsoleApp2
{
class Program
{
const string json = @"{
""0"": {
""id"": ""1"",
""email"": ""someemail@test.com"",
""tstamp"": ""2019-01-21 11:19:48"",
""times"": ""2"",
""tstamp_iso"": ""2019-01-21T12:19:48-05:00""
},
""1"": {
""id"": ""2"",
""email"": ""someotheremail@test.com"",
""tstamp"": ""2019-01-21 11:25:48"",
""times"": ""2"",
""tstamp_iso"": ""2019-01-21T12:25:48-05:00""
},
""result_code"": 1,
""result_message"": ""Success!"",
""result_output"": ""json""
}";
static void Main(string[] args)
{
JObject o = JObject.Parse(json);
List<FirstObject> l = new List<FirstObject>();
int c = 0;
while (o[$"{c}"] != null)
{
FirstObject fo = o[$"{c++}"].ToObject<FirstObject>();
l.Add(fo);
}
SecondObject so = JsonConvert.DeserializeObject<SecondObject>(json);
so.FirstObjects = l.ToArray();
Console.ReadKey();
}
}
}