如何压扁JArray的JArray?

时间:2018-05-29 19:16:36

标签: c# json json.net

我有一个JArray的JArray,但我想把它变成一个JOArray的JObjects。我已经实现了一个foreach循环,它循环遍历JArray中的每个JArray。我需要知道如何将每个子JArray压缩成一个JObject。

以下是一个例子:

[
  {
    "item": [
      {
        "fieldName": "Name",
        "value": "Andy"
      },
      {
        "fieldName": "Phone",
        "value": "678-905-9872"
      }
    ]
  },
  {
    "item": [
      {
        "fieldName": "Name",
        "value": "John"
      },
      {
        "fieldName": "Phone",
        "value": "688-954-5678"
      }
    ]
  },
  {
    "item": [
      {
        "fieldName": "Name",
        "value": "Ashley"
      },
      {
        "fieldName": "Phone",
        "value": "+44 671 542 8945"
      }
    ]
  },
  {
    "item": [
      {
        "fieldName": "Name",
        "value": "Avi"
      },
      {
        "fieldName": "Phone",
        "value": "(212)-908-7772"
      }
    ]
  }   
]

我希望每个项目都是一个JObject,从而产生以下JArray:

[
  {
      "Name": "Andy"
      "Phone": "678-905-9872"
  },
  {
      "Name": "John"
      "Phone": "688-954-5678"
  {
      "Name": "Ashley" 
      "Phone": "+44 671 542 8945"
  },
  {
      "Name": "Avi"
      "Phone": "(212)-908-7772"
  }   
]

谢谢!

修改

这是我的解决方案(c#,使用Newtonsoft.Json)

public string ParserFunction(string json)
    {
        string fieldname, fieldvalue;

        JArray jsonArray = JArray.Parse(json);

        foreach (JObject item in jsonArray)
        {
            JArray temp = (JArray)item["columns"]; //create new temporary JArray
            foreach (JObject jobject in temp)
            {
                fieldname = jobject["fieldName"].ToString();
                fieldvalue = jobject["value"].ToString();
                item.Add(fieldname, fieldvalue);
                jobject.Remove("fieldName");
                jobject.Remove("value");
            }

            item.Remove("item");

        }

        json = jsonArray.ToString();
        return json;
    }

不确定这是否是最佳方式,我看到下面的答案看起来也不错。

1 个答案:

答案 0 :(得分:1)

var jArr = new JArray(JArray.Parse(JSON)
                .Select(x => new JObject(new JProperty("Name", x["item"][0]["Name"]),
                                         new JProperty("Phone", x["item"][1]["Phone"])
                             )
                 )
            );

var str = JsonConvert.SerializeObject(jArr, Formatting.Indented);

str将是:

[
  {
    "Name": "Andy",
    "Phone": "(785) 241-6200"
  },
  {
    "Name": "Arthur Song",
    "Phone": "(212) 842-5500"
  },
  {
    "Name": "Ashley James",
    "Phone": "+44 191 4956203"
  },
  {
    "Name": "Avi Green",
    "Phone": "(212) 842-5500"
  }
]