2

I generate a JSON string in PHP and catch it with httpWebRequest in a .NET windows form application

All works well but I want to use the json.net library to cast that string back to an object (or array).

JsonSerializer serializer = new JsonSerializer();
object result = JsonConvert.DeserializeObject(responseFromServer);

How can i use that object to get the variables from the JSON string?

I've been working this out all day and couldn't find a way to get all values from the JSON string in C#

All help appreciated

kendepelchin
  • 1,963
  • 2
  • 17
  • 25

2 Answers2

3

If you create a struct in your code that matches the JSON object you can use JsonConvert.DeserializeObject<T>(String) from the Json.NET library. It's incredibly easy to use and has implementations for pretty much any .NET version.

You can also use DataContracts which requires no 3rd party library. With DataContracts there are some intermediate steps and code you need to include, but here is a site with a pretty detailed explanation: Serialization with DataContracts

Here is a link to a question here on SO that involves Json Serialization using DataContracts: SO Question

Community
  • 1
  • 1
Mike Webb
  • 8,555
  • 18
  • 77
  • 110
  • I think I just found it with the generic jsonConvert.DeserializeObject<>(json); – kendepelchin Dec 07 '11 at 20:09
  • I have a problem now when I get a list of my database. If I say 'select name,id from companies' in PHP, it returns the correct json string, but how can I catch all those arrays in C#? – kendepelchin Dec 07 '11 at 20:23
  • What is an example of the Json string? – Mike Webb Dec 07 '11 at 20:27
  • [{"name":"Electro Vergaerde","companyId":"1"},{"name":"Computers De Waele","companyId":"3"},{"name":"PC shop Maenhout","companyId":"4"},{"name":"Electro Pluis","companyId":"5"},{"name":"test","companyId":"111"}] It's all the companies, for each company there is an array containing the name and id. In C# I have a class Companies which contains two fields, name and Id. The same I did for when I wanted to catch only 1 company, but in another class. – kendepelchin Dec 07 '11 at 20:29
  • I'm such a douche: I'm answering my own questions: List result = JsonConvert.DeserializeObject>(text); Seems that I'm getting the hang out of it. First time I'm using JSON – kendepelchin Dec 07 '11 at 20:36
2

If you're on .NET 4.0 you can use dynamic along with theJavaScriptConverter class to achieve this

kprobst
  • 15,555
  • 5
  • 30
  • 53