Aviral Kumar
Aviral Kumar

Reputation: 824

deserialization of string array in c#

I have a string array of the form

"education_history":
     [{"name":"xxxxxx",
       "concentrations":[],
       "school_type":"College"},
     {"name":"xxxxxxx",
      "concentrations":[],
      "school_type":"College"}]

I want to deserialize the values name and school_type. I have already deserialized the values of single value types but I am facing problems with string arrays.One more problem is that in my request I have multiple arrays which I want to deserealize.

Thanks for the help

Upvotes: 2

Views: 1121

Answers (4)

L.B
L.B

Reputation: 116108

I think my answer to Deserialization of a Facebook JSON string also applies for this question


Instead of declaring a lot of tiny classes I would go dynamic way. Here is the code for dynamic json object. And the usage would be something like this:

dynamic obj = JsonUtils.JsonObject.GetDynamicJsonObject(jsonString);

Console.WriteLine("{0} , {1}", obj.current_location.city, obj.current_location.state);

Console.WriteLine("EDUCATION");
foreach (var eduHist in obj.education_history)
{
    Console.WriteLine("{0} , {1}", eduHist.name, eduHist.year);
}

Console.WriteLine("WORK");
foreach (var workHist in obj.work_history)
{
    Console.WriteLine("{0}  {1}-{2}", workHist.company_name, workHist.start_date, workHist.end_date);
}

Upvotes: 1

Nilesh Thakkar
Nilesh Thakkar

Reputation: 2895

Let's say you've below class :

public class EducationHistory
{
  public string name { get; set; }
  public string[] concentrations { get; set; }
  public string school_type { get; set; }
}

As already suggested by @aL3891, download Json.Net

And do like below :

EducationHistory objVal = JsonConvert.DeserializeObject<EducationHistory>(yourJsonString);

You can implement Ienumerable on above class to iterate through collection. Check out a question here, how it deserialize using Json.NET. I hope it helps!

Upvotes: 1

Kamil
Kamil

Reputation: 13931

You have to use diffrent type instead of string.

Byte array with fixed size or StringBuilder type should work.

String is variable-lenght, that is the reason of problems in deserialization.

Upvotes: 1

aL3891
aL3891

Reputation: 6275

Like marcelo said, using a json parser is the way to go: http://json.codeplex.com/

Upvotes: 1

Related Questions