hotline_emu hotline_emu - 4 months ago 24
JSON Question

C# JObject not nesting properly

I'm dealing with some issues merging my json arrays. The original arrays to be merged look similar to this:

{
"ads":[
{
"a1": "b1",
"i1": "j1",
"x1": "y1",
}
]
}

{
"ads": [
{
"a2": "b2",
"i2": "j2",
"x2": "y2",
}
]
}


The result of my merge looks similar to this:

{
"ads:[
[
{
"a1": "b1",
"i1": "j1",
"x1": "y1",
}
],
[
{
"a2": "b2",
"i2": "j2",
"x2": "y2",
}
]
]
}


What I am trying to pare this down to is:

{
"ads:[
{
"a1": "b1",
"i1": "j1",
"x1": "y1",
},
{
"a2": "b2",
"i2": "j2",
"x2": "y2",
}
]
}


The code that is being used to attempt to merge the two is currently this:

// Combine all ads within formattedContent into one single JOBject.
JToken token = null;
JArray jarray = new JArray();
List<JToken> jtokens = new List<JToken>();
foreach (JObject jobject in formattedContent)
{
token = JToken.Parse(jobject.SelectToken("ads").ToString());
jarray.Add(token);
}


But I am stuck with the doubly nested arrays when the end product is needs to result in all ads in the "ads" token under one array. Note that formattedContent in the above code is a
List<JObject>
. Any help in merging json arrays would be appreciated. Attempting to add the tokens to a string before adding them to the JArray results in carriage returns and escape characters being added in. (These are not being added while only in the debugger view [as I have seen frequently suggested], they are actually being reflected in the end product)

dbc dbc
Answer

What you want to do is to add token.Children() rather than token to jarray (i.e. add the contents of token rather than token itself):

var jarray = new JArray();
foreach (var jobject in formattedContent)
{
    var token = jobject.SelectToken("ads") as JArray;
    if (token != null)
        jarray.Add(token.Children());
}

Incidentally, you could achieve the same effect using JContainer.Merge() on the root object, with the setting JsonMergeSettings.MergeArrayHandling = MergeArrayHandling.Concat:

var merged = new JObject();
var settings = new JsonMergeSettings
{
    MergeArrayHandling = MergeArrayHandling.Concat,
};
foreach (var jobject in formattedContent)
{
    merged.Merge(jobject, settings);
}
Comments