SwethaD SwethaD - 3 months ago 6x
JSON Question

Deserialize a json string in specific format

I am trying to deserialize the JSON string below:


into the following format:

{"Header":["Code1","Code2"], "Values":[["AA","AB"],["BB","BC"],["A1","A12"],["A2","A23"],["A4","A45"],["A3","A45"]]}

I am trying to deserialize using
. I am not able to achieve the desired format.


Ah, so you have a collection of identically structured objects, and want to convert it to something akin to a CSV table (sequence of headers, then sequence of records)?

You can convert from the objects collection format to records table format using the following method:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

//other code, class declaration etc. goes here

string ObjectsToTable(string collectionJson)
    // reading the collection from passed JSON string
    JArray collection = JArray.Parse(collectionJson);

    // retrieving header as a list of properties from the first element
    // it is assumed all other elements have the exact same properties
    List<string> header = (collection.First as JObject).Properties().Select(p => p.Name).ToList();

    // retrieving values as lists of strings
    // each string is corresponding to the property named in the header
    List<List<string>> values = values = collection.Children<JObject>().Select( o => header.Select(p => o[p].ToString()).ToList() ).ToList();

    // passing the table structure with the header and values
    return JsonConvert.SerializeObject(new { Header = header, Values = values });