检索Json字符串中每条记录的值

时间:2013-10-10 11:48:23

标签: c# json loops

我目前使用以下代码检索Json字符串中第一条记录的值

string JsonString = "{'response':[{'bigINT':123456789,'smallINT':12345},{'bigINT':00000000,'smallINT':00000},{'bigINT':999999999,'smallINT':99999}]}";
JObject Jobj = JObject.Parse(JsonString);

int firstbigINT = (int)Jobj["response"][0]["bigINT"];      // 123456789
int firstsmallINT = (int)Jobj["response"][0]["smallINT"];  // 12345

这样可以正常工作,但是我希望使用类似于

的foreach迭代所有记录
foreach (string record in Jobj)
{
    int bigINT = (int)Jobj["response"][0]["bigINT"];    
    int smallINT = (int)Jobj["response"][0]["smallINT"];

    use(bigINT,smallINT)
    // then go to next record 
}

因为我需要两个值。

我尝试使用 -

JsonTextReader reader = new JsonTextReader(new StringReader(JsonString));

while (reader.Read())
{
    Console.WriteLine(reader.TokenType + " - " + reader.ValueType + " - " + reader.Value)
}

但这会将这些价值一个接一个地分开。

2 个答案:

答案 0 :(得分:0)

这不起作用吗?

string JsonString = "{'response':[{'bigINT':123456789,'smallINT':12345},{'bigINT':00000000,'smallINT':00000},{'bigINT':999999999,'smallINT':99999}]}";
        JObject Jobj = JObject.Parse(JsonString);

        foreach (var response in Jobj["response"]) 
        {
          int firstbigINT = (int)response["bigINT"];
          int firstsmallINT = (int)response["smallINT"];
          use(bigINT,smallINT)
        }

答案 1 :(得分:0)

试试这个方法

object obj = Newtonsoft.Json.JsonConvert.DeserializeObject<List<YourClassName>>(json .ToString());

这应该有效