Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read JSON data?

Tags:

json

c#

asp.net

Is this json data format?

string json = {"answer":"Line 1","mark": 1},{"answer":"Line 3","mark": 1}

I try below code but it only working with one param. ex: {"answer":"Line 1","mark": 1}. I try split json string but it isn't best way.

JObject jObject = JObject.Parse(json );

string asw = jObject["answer"].ToString();
int mark = (int)jObject["mark"];

txtAnswer.Text = asw + "////" + mark + "\n";
like image 916
P. Pogba Avatar asked Oct 27 '25 04:10

P. Pogba


2 Answers

This is a very basic JSON question which any number of tutorials could've answered for you.

Is it valid JSON ? No, and JSONLint could've told you that.

How do you read it in ?

First, wrap your JSON in square brackets so it's valid.

Then, define a class to store the records in:

public class Something
{
    public string answer { get; set; }
    public string mark { get; set; }
}

And finally, use JSON.Net to convert your string into a list of these records.

string json = "[{\"answer\":\"Line 1\",\"mark\": 1},{\"answer\":\"Line 3\",\"mark\": 1}]";

List<Something> records = JsonConvert.DeserializeObject<List<Something>>(json);         //  JSON.Net

foreach (Something record in records)
{
    System.Diagnostics.Trace.WriteLine(string.Format("Answer: {0}, Mark: {1}", record.answer, record.mark));
}

Easy as that.

like image 88
Mike Gledhill Avatar answered Oct 29 '25 19:10

Mike Gledhill


Is this json data format?

string json = {"answer":"Line 1","mark": 1},{"answer":"Line 3","mark": 1}

Nope, what you've got there doesn't look like valid C# or JSON. Try putting it inside a JSON array, then inside a proper string:

 string json = "[{\"answer\":\"Line 1\",\"mark\": 1},{\"answer\":\"Line 3\",\"mark\": 1}]";

(Hope I've got all the escaping right there.)

That's the C# escaped equivalent of the following JSON:

[{"answer":"Line 1","mark": 1}, {"answer":"Line 3","mark": 1}]

Then read up on JObject.Parse()for more info.

like image 34
Mike Chamberlain Avatar answered Oct 29 '25 19:10

Mike Chamberlain