2

i have a JSON which can for example look like this:

{
   "value":[
      {
         "Name":"Nik",
         "Age":"17",
         "Country":"Germany",
      },
      {
         "Name":"Tom",
         "Age":"20",
         "Country":"Russia",
      },
      {
         "Name":"Sila",
         "Age":"12",
         "Country":"Switzerland",

      }
   ]
}

The Keys of the properties like "Name" and "Age" are dynamic and can vary. The JSON could also look like this:

{
   "value":[
      {
         "Prename":"Nik",
         "Age":"17",
         "Country":"Germany"
         "Car":"Merc"
      },
      {
         "Prename":"Nik",
         "Age":"20",
         "Country":"Russia"
         "Car":"BMW"
      },
      {
         "Prename":"Nik",
         "Age":"12",
         "Country":"Switzerland",
         "Car":"Audi"
      }
   ]
}

The important thing is the strcuture, this is what i want to build manually with Newtonsoft.Json.

This is my current attempt:

var jArray = new JArray();
jArray.Add("Name");
jArray.Add("Nikola");

jArray.Add("Age");
jArray.Add("17");

jArray.Add("Country");
jArray.Add("Germany");

JObject o = new JObject();
o["Value"] = jArray;

string json = o.ToString();

Result:

{
  "Value": [
    "Name",
    "Nikola",
    "Age",
    "17",
    "Country",
    "Germany"
  ]
}

I tried to solve it with this example from the newtonsoft Website, but as you can see it's really poor explained.

  • 2
    Wouldn't it be easier to paste the JSON into Visual Studio, have it auto-generate a class that you can then fill and serialize at runtime without having to know anything about JSON's nitty gritty? –  Apr 07 '21 at 10:39
  • 3
    you need to add Jobjects to your array, and each object, you add properties – Keith Nicholas Apr 07 '21 at 10:40
  • 2
    @MickyD: No need for a class here - just `var obj = new { value = new[] { Name = "Nik", Age = "12", Country = "Germany" } };` etc would be enough. If the OP wants to parse and then use the JSON, then using a class would make sense (although I'd probably just write it manually - it'll be trivial) but just for production, anonymous types are really useful. – Jon Skeet Apr 07 '21 at 10:42
  • @MickyD the thing is, I get data, which can vary from amount type. So it is not given for me that i always have a "Name" Key. I have to get the data and then build the JSON structure i provideded above manually. I didn't mention this, because i thought i would be out of the frame. – Nikola Mitrovic Apr 07 '21 at 10:44
  • @NikolaMitrovic: It sounds like there's quite a lot of context which is missing then... all we can really suggest is "use `JObject` to represent each object". With more information in the question, we're likely to be able to help you more. – Jon Skeet Apr 07 '21 at 10:48
  • @JonSkeet I see what you mean, I updated the question. – Nikola Mitrovic Apr 07 '21 at 10:55
  • We still have no idea how you're receiving the information, which still makes it very hard to even imagine what a useful answer would look like, beyond the very general "use JObject". – Jon Skeet Apr 07 '21 at 10:56
  • It seems you are stuck on using `JObject`, but with context I feel like this could be solved with a much more appropriate solution. For example, the keys and values of your individual items could be taken from a Dictionary, that way things are still dynamic and you get to use a concrete class. – DavidG Apr 07 '21 at 10:57
  • @JonSkeet I wrote a new question were i am really specific, i thought to live this question as it is, because it still might help other people. https://stackoverflow.com/questions/66985340/transform-excel-data-into-specific-json-format – Nikola Mitrovic Apr 07 '21 at 11:41

4 Answers4

6

You need to add JObject into the array like so. I imagine you you will have to add whatever condition properties (or other nested objects) you want

var jArray = new JArray();
var nik = new JObject();
nik["Name"] = "nik";
nik["Age"] = "17";
nik["Country"] ="Germany";

jArray.Add(nik);
JObject o = new JObject();
o["Value"] = jArray;

string json = o.ToString();

depending on the exact nature of your dynamic content, you can use intializer code like

    var jArray = new JArray
    {
        new JObject {["Name"] = "nik", ["Age"] = "17", ["Country"] = "Germany"},
        new JObject {["Name"] = "bob", ["Age"] = "32", ["Country"] = "New Zealand"}
    };
    var o = new JObject {["Value"] = jArray};
Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
1

If you want to construct your object dynamically you can use dictionary:

var jsonObj = new Dictionary<string, List<Dictionary<string, string>>>
{
    {
        "Value", new List<Dictionary<string, string>>
        {
            new Dictionary<string, string>
            {
                {"Prename", "Nik"},
                {"Age", "17"},
                {"Country", "Germany"},
                {"Car", "Merc"}
            },
            new Dictionary<string, string>
            {
                {"Prename", "Nik"},
                {"Age", "20"},
                {"Country", "Russia"},
                {"Car", "BMW"}
            },
            new Dictionary<string, string>
            {
                {"Prename", "Nik"},
                {"Age", "12"},
                {"Country", "Switzerland"},
                {"Car", "Audi"}
            }
        }
    }
};
var json = JsonConvert.SerializeObject(jsonObj);
Console.WriteLine(json);
godot
  • 3,422
  • 6
  • 25
  • 42
1

You could consider creating it from an anonymous object instead, like this:

JObject o = JObject.FromObject(new
{
    value = new [] {
        new {
            Name = "Nik",
            Age = "17",
            Country = "Germany"
        },

        new {
            Name = "Nik1",
            Age = "18",
            Country = "Austria"
        },
    }
});

string json = o.ToString();

It produces this result:

{
  "value": [
    {
      "Name": "Nik",
      "Age": "17",
      "Country": "Germany"
    },
    {
      "Name": "Nik1",
      "Age": "18",
      "Country": "Austria"
    }
  ]
}
MikNiller
  • 1,242
  • 11
  • 17
1

I believe the exact structure you are looking to achieve is:

    //New Json Array
    var manualJSON = new JArray();

    //Add Nik
    var NIK = new JObject();
    NIK["Name"] = "Nik";
    NIK["Age"] = "17";
    NIK["Country"] = "Germany";

    //Add Tom
    var Tom = new JObject();
    Tom["Name"] = "Tom";
    Tom["Age"] = "20";
    Tom["Country"] = "Russia";
    
    //Add People to Json Array
    manualJSON.Add(Tom);
    manualJSON.Add(NIK);

    //Pass your json to a new object to print
    JObject o = new JObject();
    o["value"] = manualJSON;

    //Live Testing
    string json = o.ToString();
    File.WriteAllText("test.txt", json);
    Process.Start("test.txt");
MrJack Mcfreder
  • 692
  • 1
  • 10
  • 21