0

I'm having some issues with fetching json values in c#.

https://i.sstatic.net/Uxn8e.png

Here is the code in question:

var json2 = new WebClient().DownloadString("http://fetch.json.url.here" + Input_Textbox.Text);
JObject o2 = JObject.Parse(json2);

string he_ident = (string)o2["he_ident"];
string le_ident = (string)o2["le_ident"];

Console.WriteLine(he_ident);
Console.WriteLine(le_ident);

Line 204 is: JObject o2 = JObject.Parse(json2);

The json is this: [{"le_ident":"06L","he_ident":"24R"},{"le_ident":"06R","he_ident":"24L"},{"le_ident":"07L","he_ident":"25R"},{"le_ident":"07R","he_ident":"25L"}]

I've also tried with just one set of le_ident and he_ident, such as [{"le_ident":"06L","he_ident":"24R"}] but it sill throws the same error.

Any ideas?

1
  • Since it looks like you're using JSON.Net, have you tried just using JsonConvert.Deserialize() in an alternative solution? Commented Jul 8, 2013 at 4:35

3 Answers 3

1

Personally, the cleanest approach to take is to define a class for the object signature you're expecting to take in:

class Entity {
    public he_ident { get;set; }
    public le_ident { get;set; }
}

Then just call DeserializeObject() into a collection:

var entities = JsonConvert.DeserializeObject<List<Entity>>(json2);

You should be able to access that then just like any C# object:

foreach(var entity in entities) {
    Console.WriteLine(entity.he_ident);
    Console.WriteLine(entity.le_ident);
}

This won't work if your JSON signature is dynamic though (or will be a bit tedious, as you'd have to define classes for each of your signatures).

But personally, I find that this approach does away with the muckiness that stuff like ArrayList had, and introduces strict typing into your code, which I find to generally lend itself to stronger, cleaner structure in a C# environment.

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

Comments

1

You should use JArray instead of JObject for json arrays:

    var json = new WebClient().DownloadString(...);
    JArray array = JArray.Parse(json);
    string he_ident = (string)array[0]["he_ident"]; 
    string le_ident = (string)array[0]["le_ident"];

Comments

0

That JSON is a list not a dictionary.

So what you need to do is this:

string he_ident = (string)(((ArrayList)o2)[0])["he_ident"];

(Or simply loop through the list)

The JSON data:

{"le_ident":"06L"}

Should work with the code you have there.

1 Comment

I gave it a shot, but it throws this error: Cannot convert type 'Newtonsoft.Json.Linq.JObject' to 'System.Collections.ArrayList'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.