0

While attempting to extract data from JSON using JavaScriptSerializer, particular difficulties are encountered while looking through the data of object type. Based on the below sample data, the following code has been written:

var serializer = new JavaScriptSerializer();
dynamic outp = serializer.DeserializeObject(out3);            
var a = outp["Number"]; // is OK, returns "1"
var b = outp["Description"]; // stuck in looking through "Description" to access "address", then extract the value of "street_2", as an illustration.

Feedback (not involving ideally the definition of a class with related properties) would highly be appreciated. Thanks.

{
  "Number": 1,
  "Description": [
    {
      "id": "PO1234",
      "country": "TE",
      "No": "4050",
      "safeNo": "LU37",
      "name": "stuck",
      "address": {
        "street_1": "adhoc, 0098, country",
        "street_2": "94 street",
        "city": "stackoverflow",
        "zip": "stack"
      },
      "is_EU": "Y",
      "conti": "E",
      "date": "2019-08-14T21:43:02.000Z"
    }
  ]
}
3
  • not involving ideally the definition of a class, is this because the JSON is dynamic? Commented Apr 11, 2020 at 16:44
  • Not at all. I guess (modest opinion), that solutions involving dictionaries would relatively be more efficient, particularly if one have many data from different queries to be extracted. Commented Apr 11, 2020 at 16:49
  • I think using a class then is the neatest option. But that's just my opinion. Commented Apr 11, 2020 at 16:58

2 Answers 2

1

Since Description is an array, you can egt the first item by index and access its properties by key, in the same way with Number. Under the hood every item of Description (as well as address) is Dictionary<string, object>

var serializer = new JavaScriptSerializer();
dynamic outp = serializer.DeserializeObject(out3);  

var a = outp["Number"]; 
var b = outp["Description"][0];
var name = b["name"];
var street = b["address"]["street_2"];

However, using JavaScriptSerializer isn't recommended, you should use Json.Net instead

Sign up to request clarification or add additional context in comments.

1 Comment

Very smart approach with the indexation (:) , and your tip in relation to JavaScripSerializer has been appreciated. Many thanks, Pavel.
0

You can use Newtonsoft.Json to deserialize it like that:

static string Test()
{
    var filePath = "../../../response.json";
    var text = File.ReadAllText(filePath);

    var result = JsonConvert.DeserializeObject<JObject>(text);

    var data = result
        .GetValue("Description")
        .Select(t => t.Value<JObject>("address"))
        .First()
        .Value<string>("street_2");

    return data;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.