I am not Fat
I am not Fat

Reputation: 447

How do I append an JsonProperty to another JsonProperty

I have this JsonDocument which looks like this

string jsonString = "{\"year\": 0, \"class\": [], \"schools\": []}";
JsonDocument newSchema = JsonDocument.Parse(jsonString)

And a bunch of JSON files, with these properties filed out. Each of the JSON file have the same year, but contain information of one specific class and one specific school. None of the them is the same beside the year.

I trying to create a one JsonDocument with all class and schools put together into one JsonDocument, but seem to have a problem with appending the JsonProperty together..

This is what I have tried so far:

using (JsonDocument newSchema = JsonDocument.Parse(jsonString))
{
    List<JsonProperty> properties = new List<JsonProperty>();
    foreach(JsonProperty a in newSchema.RootElement.EnumerateObject())
    {
        properties.Add(a);
    }
    foreach (string classandSchoolDefinition in loadableSchemaDefinitions)
    {

        string schemaDefinitionAsJson = File.ReadAllText(classandSchoolDefinition );
        JsonDocument schemaJson = JsonDocument.Parse(schemaDefinitionAsJson);

        foreach (JsonProperty a in schemaJson.RootElement.EnumerateObject())
        {
            switch (a.Name)
            {
                case "year":
                    Console.WriteLine($@"({a.Name}+{a.Value}, {a.Value.ValueKind})");
                    break;
                case "class":
                    Console.WriteLine($@"({a.Name}+{a.Value}, {a.Value.ValueKind})");
                    break;
                case "school":
                    Console.WriteLine($@"({a.Name}+{a.Value}, {a.Value.ValueKind})");
                    break;
                default:
                    break;
            }
        }
    }

How do I concat each the Jsonproperty value to one combined newSchema, and not keep the into one?
In this case I only want append an array to another array.

Upvotes: 0

Views: 300

Answers (1)

mvSapphire
mvSapphire

Reputation: 95

You can reach this with Newtonsoft.Json

For example, you have

var o1 = JObject.Parse(@"{
  'Name': 'Max',
  'Enabled': false,
  'Roles': [ 'User' ]
}");

and another object

var o2 = JObject.Parse(@"{
  'Enabled': true,
  'Roles': [ 'User', 'Admin' ]
}");

simply use Merge function like this -

o1.Merge(o2, new JsonMergeSettings
{
    // to avoid duplicates
    MergeArrayHandling = MergeArrayHandling.Union
});

the result will be -

{
   "FirstName": "Max",
   "Enabled": true,
   "Roles": [
      "User",
      "Admin"
  ]
}

Upvotes: 1

Related Questions