简体   繁体   中英

How do I get properties in the array in this JSON string?

In the JSON string below, how do I access the values of the "at" and "current_value" properties within the "datastreams" array ?

In this example, there is only one datastream but in reality there could be many. I need to access the datastream by "id" property. Once I figure out this issue, I plan to use a where clause with the id == to the id of the desired datastream.

I tried using the approach discussed here , under "JSON in Windows 8 – A Simpler Approach" but it's not working.

In this code, json contains the JSON returned from the service I'm calling. prop is populated with a JsonArray . current results in an exception with an inner message of "JSON value not found"

var json = JsonObject.Parse(responseBodyAsText);
var prop = json.GetNamedArray("datastreams");

var current = from p in prop
    select new
    {
       datastream = p.GetObject().GetNamedString("datastreams"),
       datetime = p.GetObject().GetNamedString("at"),
       value = p.GetObject().GetNamedString("current_value")
    };

Here is the JSON string:

{
   "title":"X",
   "status":"X",
   "creator":"X",
   "datastreams":
      [
         {
            "at":"x",
            "max_value":"X",
            "current_value":"X",
            "id":"X",
            "min_value":"X"
         }
      ],
   "location":{"exposure":"x","domain":"x","disposition":"x","lat":X,"lon":-X},
   "created":"X",
   "tags":["X"],
   "feed":"X",
   "private":"X",
   "id":X,
   "description":"X",
   "version":"X",
   "updated":"X"
}

datastream = p.GetObject().GetNamedString("datastreams")

The code above should return an array of objects. You'll need to loop through the array of objects to check the value of each object's "at" and "current_value" properties.

datastream return an array as you can notice by [ ] so:

datetime = datastream[0].at
value = datastream[0].current_value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM