如何读取JSON数据? [英] How to read JSON data?
问题描述
这是json数据格式吗?
Is this json data format?
string json = {"answer":"Line 1","mark": 1},{"answer":"Line 3","mark": 1}
我尝试下面的代码,但它仅适用于一个参数.例如:{"answer":"Line 1","mark": 1}
.我尝试拆分json字符串,但这不是最好的方法.
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";
推荐答案
这是一个非常基本的JSON问题,许多教程都可以为您解答.
This is a very basic JSON question which any number of tutorials could've answered for you.
它是有效的JSON吗?不, JSONLint 可以告诉你.
Is it valid JSON ? No, and JSONLint could've told you that.
您如何阅读它?
首先,将您的JSON放在方括号中,这样它才有效.
First, wrap your JSON in square brackets so it's valid.
然后,定义一个class
以便将记录存储在以下位置:
Then, define a class
to store the records in:
public class Something
{
public string answer { get; set; }
public string mark { get; set; }
}
最后,使用JSON.Net将您的字符串转换为这些记录的列表.
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));
}
那样简单.
这篇关于如何读取JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!