-2

我正在尝试将 JSON 数组转换为对象格式。

例子:

{
  "country": "USA",
  "date": "2019-6-30",
  "Speaker": [
    {
      "id": "name",
      "value": "Tiger"
    },
    {
      "id": "age",
      "value": "35"
    },
    {
      "id": "topic",
      "value": ".NET"
    }
  ]
}

我想将其转换为:

{
  "country": "USA",
  "date": "2019-6-30",
  "name": "Tiger",
  "age": 35,
  "topic": ".NET"
}

我尝试了几种方法,但没有运气。看来我无法获得内部数组的值。请帮忙。

4

3 回答 3

0

你只需要几个类来反序列化这个 JSON,例如:

public class Data
{
    public string Country { get; set; }
    public string Date { get; set; }

    // Deserialise the array as a list of 'SpeakerItem'
    public List<SpeakerItem> Speaker { get; set; }

    // These will throw exceptions if the id doesn't match, but it's a start
    public string Name => Speaker.Single(s => s.Id == "name").Value;
    public string Age => Speaker.Single(s => s.Id == "age").Value;
    public string Topic => Speaker.Single(s => s.Id == "topic").Value;
}

public class SpeakerItem
{
    public string Id { get; set; }
    public string Value { get; set; }
}

现在您可以执行以下操作:

var value = JsonConvert.DeserializeObject<Data>(json);
于 2019-09-18T00:04:31.017 回答
0

我使用 JSON.Net 有类似的东西,首先你的 json 是错误的(你在国家线的末尾有点)。我使用过 DynamoObjects。

string json = @"
            {
                ""country"": ""USA"",
   ""date"": ""2019-6-30"",
    ""Speaker"" : [
    {
        ""id"": ""name"",
        ""value"": ""Tiger""
    },
    { 
        ""id"": ""age"",
        ""value"": ""35""
    },
    { 
        ""id"": ""topic"",
        ""value"": "".NET""
    },
    ] 
}";
            dynamic animalJson = JsonConvert.DeserializeObject<dynamic>(json);
            dynamic animal = new ExpandoObject();
            animal.country = animalJson.country;
            animal.date = animalJson.date;
            animal.name = animalJson.Speaker[0].value;
            animal.age = animalJson.Speaker[1].value;
            animal.topic = animalJson.Speaker[2].value;
            string modifiedAnimalJson = JsonConvert.SerializeObject(animal);
于 2019-09-18T00:26:44.817 回答
0

您可以使用 Json.Net 的LINQ-to-JSON API (JObjects) 来转换您的 JSON:

JObject root = JObject.Parse(json);
JProperty arrayProp = root.Properties()
                          .Where(jp => jp.Value.Type == JTokenType.Array)
                          .FirstOrDefault();
if (arrayProp != null)
{
    foreach (JObject item in arrayProp.Value.Children<JObject>())
    {
        root[(string)item["id"]] = item["value"];
    }
    arrayProp.Remove();
}

json = root.ToString();

此解决方案不依赖于具有任何特定名称的数组属性,也不关心项目 ID 是什么。但是,如果数组中的任何 id 与根对象中的现有属性重叠,则数组中的值将替换根对象中已经存在的值。同样,如果数组中有任何重复的 id,最后一个将“获胜”。

工作演示:https ://dotnetfiddle.net/p3WkqN

于 2019-09-18T00:46:11.390 回答