0

The following bit of code attempts to read some json and populate an object:

public Response ParseObject(string Json)
    {


        Response response = new Response();
        JsonConvert.PopulateObject(Json, response);
        return response;


    }

Here's the Response object:

 public class Response
{
    public string id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public string status { get; set; }
    public string incorporationDate { get; set; }
    public string latestAnnualReturnDate { get; set; }
    public string latestAccountsDate { get; set; }
    public string companyType { get; set; }
    public string accountsType { get; set; }

Unfortunately, the object (response) is empty ie (response.id is null as are all of the other properties).

I'm guessing that I need to pass in some JsonSerializerSettings but I can't find a tutorial anywhere?

BIDeveloper
  • 2,594
  • 4
  • 34
  • 51

2 Answers2

1

You might want to check your Json string. When I run your code with the below set-up I get the values in the Response object.

        var s = "{ \"id\":\"2\" , \"name\":\"Doe\" }";
        Response response = ParseObject(s); 
Spock
  • 6,821
  • 1
  • 36
  • 58
  • From @danywalls link this was the key: using (WebClient wc = new WebClient()) { var json = wc.DownloadString("http://coderwall.com/mdeiters.json"); var user = JsonConvert.DeserializeObject(json); } – BIDeveloper Jun 20 '13 at 14:52
0

Response Try to use the above. This is to get the string from HttpContext

  Stream dataStream = context.Request.InputStream;
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            Response  data =(Response )json_serializer.DeserializeObject(responseFromServer);

In your case you can use

 JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            Response  data =(Response )json_serializer.DeserializeObject(Json);
kostas ch.
  • 1,870
  • 1
  • 16
  • 28