使用JSON.NET解析JSON键/值对 [英] Parsing JSON key/value pairs with JSON.NET

查看:183
本文介绍了使用JSON.NET解析JSON键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.NET项目.我正在使用JSON.NET库.我需要使用此库来解析一些JSON.我的JSON看起来像这样:

I have a .NET project. I'm using the JSON.NET library. I need to use this library to parse some JSON. My JSON looks like this:

{"1":"Name 1","2":"Name 2"}

该对象实际上只是键/值对的列表.我试图弄清楚如何使用JSON.NET来1)解析此JSON和2)遍历键/值对.有没有办法做到这一点?如果可以,怎么办?

The object is really just a list of key/value pairs. I am trying to figure out how to use JSON.NET to 1) parse this JSON and 2) loop through the key/value pairs. Is there a way to do this? If so, how?

我唯一看到的是反序列化为强类型对象.

The only thing I see is de-serializing into a strongly-typed object.

非常感谢您!

推荐答案

您可以反序列化为Dictionary<string, string>

var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
foreach(var kv in dict)
{
    Console.WriteLine(kv.Key + ":" + kv.Value);
}

由于JObject实现了IDictionary,因此您也可以简单地使用JObject.Parse

Since JObject implements IDictionary, you can also simply use JObject.Parse

var dict = JObject.Parse(@"{""1"":""Name 1"",""2"":""Name 2""}");

这篇关于使用JSON.NET解析JSON键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆