Search code examples
c#jsonjson.net

Convert JSON array into another structure


I am looking for a solution where I can convert the JSON structure with C#. Currently, I am trying to convert this JSON structure using the Newtonsoft library but I'm not finding any solution.

Below JSON needs to be converted:

[
    [
        {
            "FieldName": "Id",
            "Value": 1234
        },
        {
            "FieldName": "FieldName1",
            "Value": 2722
        },
        {
            "FieldName": "FieldName2",
            "Value": "2022-06-21T13:03:11.5958542Z"
        },
        {
            "FieldName": "FieldName3",
            "Value": "XYZ"
        }
    ]
]

Required JSON structure from above JSON:

[
    {
        "Id": 1234,
        "FieldName1" : 2722,
        "FieldName2" : "2022-06-21T13:03:11.5958542Z",
        "FieldName3" : "XYZ"
    }
]

Solution

  • You have to iterate over your inner array.

    A single JObject has to be created and in the loop filled with the data from your input array.

    The data type of the value has to be checked: int.TryParse
    In the case of boolean values, the if condition has to be extended.

    public void Transform()
    {
        var data = "[ [ { \"FieldName\": \"Id\", \"Value\": 1234 }, { \"FieldName\": \"FieldName1\", \"Value\": 2722 }, { \"FieldName\": \"FieldName2\", \"Value\": \"2022-06-21T13:03:11.5958542Z\" }, { \"FieldName\": \"FieldName3\", \"Value\": \"XYZ\" } ] ]";
    
        var input = JArray.Parse(data);
        var inputFirst = input[0] as JArray;
    
        var outputItem = new JObject();
    
        foreach (JObject item in inputFirst)
        {
            var fieldName = item["FieldName"].Value<string>();
            var fieldValue = item["Value"].Value<string>();
    
            if (int.TryParse(fieldValue, out int fieldIntValue))
            {
                outputItem[fieldName] = fieldIntValue;
            }
            else
            {
                outputItem[fieldName] = fieldValue;
            }
        }
    
        var output = new JArray();
        output.Add(outputItem);
    
        var result = output.ToString();
        Console.WriteLine(result);
    }
    

    Console.WriteLine(result); writes following JSON:

    [
      {
        "Id": 1234,
        "FieldName1": 2722,
        "FieldName2": "06/21/2022 13:03:11",
        "FieldName3": "XYZ"
      }
    ]