Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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"}

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.

Thank you so much!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
206 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can deserialize to Dictionary<string, string>

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...