Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON key/value pairs with JSON.NET

Tags:

json

c#

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!

like image 793
JQuery Mobile Avatar asked Apr 14 '15 16:04

JQuery Mobile


People also ask

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings.

What is Jsonconvert DeserializeObject?

DeserializeObject<T>(String,JsonConverter[]) Deserializes the JSON to the specified . NET type using a collection of JsonConverter.


1 Answers

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""}"); 
like image 169
EZI Avatar answered Sep 22 '22 19:09

EZI