skip to Main Content

I use newton’s json of C#.
Before I start, I know a bit about the json form, but I’m not sure I know it perfectly.
Therefore, the corresponding json form may be an incorrect json form.

This is json’s sample data.

{ "data" :
  [
    [
      {
        "key1":"value1",
        "key2":"value2"
      },{
        "key1":"value3",
        "key2":"value4"
      }
    ],[
      {
        "key10":"value10"
      }
    ]
  ]
}

This json data is the current JObject Type.
I would like to receive this JObject in the following string form.

    [
      {
        "key1":"value1",
        "key2":"value2"
      },{
        "key1":"value3",
        "key2":"value4"
      }
    ],[
      {
        "key10":"value10"
      }
    ]

I tried this code.

    //JObject jobj = /*Sample json*/;
    string json = (jobj["data"] as JArray)[0].ToString();

This code returns the following results.

    [
      {
        "key1":"value1",
        "key2":"value2"
      },{
        "key1":"value3",
        "key2":"value4"
      }
    ]

2

Answers


  1. Note that your desired result is not valid JSON. It is two JSON arrays, separated by a comma. There is no single "root" element.

    So to produce your desired output, just join the arrays’ string representations with commas. string.Join does exactly that.

    if (jobj["data"]?.Values<JArray>() is IEnumerable<JArray?> arrays)
    {
        Console.WriteLine(string.Join(",", arrays));
    }
    
    Login or Signup to reply.
  2. You can use Newtonsoft.Json.Linq to Deserialize the input string into a JToken as below.

    var result = JsonConvert.DeserializeObject<JToken>(res);
    

    And retrieve the "data" list as below.

    var _data = (JArray)result["data"];
    

    OR

    var _data = result["data"].ToList();
    

    If you want to convert it to a string, you can use .ToString() as below

    string _data = result["data"].ToString();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search