0

I am fetching a string from a JSON file & want to convert it to Key-Value pair.

I am using JSON.NET for the same.

I know I can deserialize a List using:

List<JsonClass> jsonFileComments = JsonConvert.DeserializeObject<List<JsonClass>>(json); 

And I can Deserialize a Array using:

Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); 

But as my JSON string contains Lists & Arrays in single file only. The sequence is like:

{ List, List, List, Array, List, Array, List } 

Can you tell me how can I deserialize it using single way.

Other way is I need to separate out the Arrays & work on separately. And again while Serializing I need to work that stuff.

1
  • Most of the time you'd deserialize a JSON string into a specific C# type. Can you show the JSON you're working with? Commented Feb 9, 2015 at 14:11

2 Answers 2

1

Well one way would be to use dynamic(The type is a static type, but an object of type dynamic bypasses static type checking.)?

dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}"); Console.WriteLine(d.number); Console.WriteLine(d.str); Console.WriteLine(d.array.Count); 
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Margus, This dynamic keyword works in Windows Application but when I went to Web Application where I want to use it actually, it throws error saying "Dynamic operations can only be performed in homogenous AppDomain."....Any suggestion?
@SanjayAdsure Are you running your application on pre .net4.0 ? You can try to load it into a different appdomain (bryancook.net/2010/02/running-code-in-separate-appdomain.html)
I am using .NET 4.5 with SharePoint 2013
0

Hope this code block helps. I'm assuming you have jSon object & you need to parse through it:

Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(yourJsonData); Newtonsoft.Json.Linq.JArray textArray = (Newtonsoft.Json.Linq.JArray)o["yourArray"]; if (textArray.Count > 0) { for (int i = 0; i < textArray.Count; i++) {//do something} } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.