VladacusB
VladacusB

Reputation: 844

Cannot identify data structure from JSON to deserialize into object

Having issue with deserializing json string into object. The main issue is that I can not identify what type of object this string represents:

string jsonDataText = @"{""sun"":""heat"", ""planet"":""rock"", ""earth"":""water"", ""galaxy"":""spiral""}";

It looks like List of KeyValuePair objects, but when I try to deserialize by using Newtonsoft.Json:

var clone = JsonConvert.DeserializeObject<List<KeyValuePair<string,string>>>(jsonDataText);

I have got an exception:

 Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[System.Collections.Generic.KeyValuePair`2[System.String,System.String]]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

Had also tried with Maps and string(multidimensional) arrays but got the same exception...

Upvotes: 0

Views: 84

Answers (3)

er-sho
er-sho

Reputation: 9771

With using JObject its easy to read any key/value pair from JSON.

So you no more need to identify what the type of your key/value pair in your json.

string jsonDataText = @"{""sun"":""heat"", ""planet"":""rock"", ""earth"":""water"", ""galaxy"":""spiral""}";

//Parse your json to dictionary
Dictionary<string, string> dict = JObject.Parse(jsonDataText).ToObject<Dictionary<string, string>>();  

You need to add this namespace to your program => using Newtonsoft.Json.Linq;

Output:

enter image description here

Upvotes: 0

Pablo notPicasso
Pablo notPicasso

Reputation: 3161

It looks like Dictionary< string,string > to me.

 JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonDataText);

Upvotes: 2

Tor
Tor

Reputation: 631

It looks like to me as a simple class.

public class MyClass
{
    [JsonProperty("sun")]
    public string Sun { get; set; }

    [JsonProperty("planet")]
    public string Planet { get; set; }

    [JsonProperty("earth")]
    public string Earth { get; set; }

    [JsonProperty("galaxy")]
    public string Galaxy { get; set; }
}

Deserialize:

var clone = JsonConvert.DeserializeObject<MyClass>(jsonDataText);

Upvotes: -1

Related Questions