Detailed explanation of of the method of converting json string into object with Newtonsoft

  • 2021-12-11 18:42:45
  • OfStack

First, turn the json string into an JObject object:


JObject jo = (JObject)JsonConvert.DeserializeObject(CurrentSelectedItemReq);

This JObject is a "value pair" type, for example, our json string is like this:


{
 "rows":[
  [
   {"NumIid":"001"},
   {"PicUrl":"xxx.png"},
   {"Title":"xxxxx"},
   {"Price":"xxx"},
   {"OuterId":"xxxx"} 
  ],
  [
   {"NumIid":"002"},
   {"PicUrl":"xxx.png"},
   {"Title":"xxxxx"},
   {"Price":"xxx"},
   {"OuterId":"xxxx"} 
  ],
  [
   {"NumIid":"003"},
   {"PicUrl":"xxx.png"},
   {"Title":"xxxxx"},
   {"Price":"xxx"},
   {"OuterId":"xxxx"} 
  ]
  ]
}

Then jo ["rows"] is an array. If this is not an array, it may be an object, then we cast it according to what value it is actually.

Taking the above json string as an example, we get this array as follows:

JArray arr = (JArray)jo["rows"];

We find that there is still an array in this array, and there is an object in the inner array, so we can take it like this:


for (int i = 0; i < arr.Count; i++) 
    {
      JArray arr2 = (JArray)arr[i];
      for (int j = 0; j < arr2.Count; j++) 
      {
        JObject obj = (JObject)arr2[j];

        Response.Write(obj["NumIid"]);
        Response.End();
      }
        
    }

If it's actually an array, we cast it with JArray, and if it's actually a pair of values, we cast it with JObject.

The last layer should be object of a value pair type. How to take out all these values?

Finally, it should be shaped like:

{"NumIid":"003"}

The value is simple and direct:

string str=obj["NumIid"];

The problem is that sometimes this obj looks like this:

{"PicUrl":"xxx.png"}

And you don't know when and what he is.

At this time, it should be taken like this:


foreach (KeyValuePair<string, JToken> kp in obj) 
        {
          Response.Write(kp.Key);
          Response.Write("=");
          Response.Write(kp.Value);
          Response.End();
        }


Related articles: