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!
SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings.
DeserializeObject<T>(String,JsonConverter[]) Deserializes the JSON to the specified . NET type using a collection of JsonConverter.
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""}");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With