Home > Mobile >  Get Values From Array in Json String
Get Values From Array in Json String

Time:02-19

I'm receiving json strings that typically look something like this:

[{
    "objectName": "UDO_Job",
    "primaryKey": "123456789",
    "UDO_JobPart": [{
        "length": "24.0",
        "width": "24.0",
        "qty": "12"
    }, {
        "length": "24.0",
        "width": "24.0",
        "qty": "1"
    }, {
        "length": "36.0",
        "width": "34.0",
        "qty": "3"
    }]
}]

I need to retrieve the primaryKey value, then the contents of each element of the UDO_JobPart array (length, width, and qty).

I am able to get the primaryKey value with this code:

var jArray = JArray.Parse(json);
int primaryKey = jArray[0]["primaryKey"].Value<int>();

But I'm hitting a wall with getting the contents of the array. I tried something like this:

double length = jArray[0]["UDO_JobPart"][0].["length"].Value<double>();

But I'm not getting anything back. Any advice would be greatly appreciated.

CodePudding user response:

Remove . between [0] and [length].

double length = jArray[0]["UDO_JobPart"][0]["length"].Value<double>();

Sample Program


Split from 1 line code above, the structure is as (for better understanding):

var jArray = JArray.Parse(json);
var jObj = jArray[0];
var jobPart = jObj["UDO_JobPart"][0];
double length = jobPart["length"].Value<double>();

Sample program

CodePudding user response:

Have you tried JPath, may be it is cleaner approach,

double value = jSONArray
     .SelectToken("$.[0].UDO_JobPart[0].length")
     .Value<double>();

Try Online


More Details: JSON-Path Repo #Operators

  • Related