colourtheweb
colourtheweb

Reputation: 767

C# How to combine multiple JSON arrays that are part of a List?

What has been done so far?

I am working on dividing up the number of records into 3 batches and processing them in parallel to increase the performance. However, after processing the batches in parallel I would also like to save the outcome (JSON string) of the processed records in a variable.

As you can see below, I first initialize the variable as List of string and then run the foreach loop which saves the processed outcome as mentioned below.

List<string> responseOutcome = new List<string>();

Parallel.ForEach(recordBatches, batch => { 
    responseOutcome.Add(response1.Content);
});

Result in List responseOutcome comes as:

responseOutcome[0]

[
  {
    "Name": "Sample1",
    "ID": "123"
  },
  {
    "Name": "Sample2",
    "ID": "394"
  }
],

responseOutcome[1]

[
  {
    "Name": "Sample5",
    "ID": "384"
  },
  {
    "Name": "Sample6",
    "ID": "495"
  }
],

responseOutcome[2]

[
  {
    "Name": "Sample3",
    "ID": "473"
  },
  {
    "Name": "Sample4",
    "ID": "264"
  }
]

What I would like to achieve? Now I would like to take the value of responseOutcome which is multiple arrays of JSON string and merge them into one big JSON string.

Final Output

    [
      {
        "Name": "Sample1",
        "ID": "123"
      },
      {
        "Name": "Sample2",
        "ID": "394"
      },
      {
        "Name": "Sample5",
        "ID": "384"
      },
      {
        "Name": "Sample6",
        "ID": "495"
      },
      {
        "Name": "Sample3",
        "ID": "473"
      },
      {
        "Name": "Sample4",
        "ID": "264"
      }
    ]

I looked into several similar cases but they weren't nearly similar. Like:

How do I merge multiple json objects

How do I combine two arrays from two JObjects in Newtonsoft JSON.Net?

Any help/guidance will be great!!

Upvotes: 0

Views: 1593

Answers (2)

Connell.O&#39;Donnell
Connell.O&#39;Donnell

Reputation: 3693

Using Newtonsoft, you can create a JArray from each of your responses. Then you can flatten the hierarchy using linq's SelectMany method and re-serialize the object.

Try this:

var obj = responses.Select(r => JArray.Parse(r.Trim(','))).SelectMany(token => token);
string json = JsonConvert.SerializeObject(obj, Formatting.Indented);

Upvotes: 1

Bryan Lewis
Bryan Lewis

Reputation: 5977

There are probably more efficient ways to do this if you want to do pure string manipulation, but using Newtonsoft, I would deserialize, merge and then re-serialize.

Create a small POCO model:

public class ResponseOutcomeModel
{
    public string ID { get; set; }
    public string Name { get; set; }
}

Then deserialize to this model, merge and reserialize to JSON as a single list.

var outcomeList = new List<ResponseOutcomeModel>();
foreach (var i in responseOutcome)
{
   outcomeList.AddRange(JsonConvert.DeserializeObject<List<ResponseOutcomeModel>>(i.Trim().TrimEnd(',')));
}

var finalJson = JsonConvert.SerializeObject(outcomeList);

Note, the Time/TrimEnd is used if the trailing commas in your example are really there in your responseOutcome array (at the end of each element in the array). The call to DeserializeObject will complain if you leave the commas in there.

Upvotes: 0

Related Questions