10

I would like to deserialize a string o JSON and output data on a string:

public class Test
{
    public int id { get; set; }
    public string name { get; set; }
    public long revisionDate { get; set; }
}

private void btnRetrieve_Click(object sender, EventArgs e)
{
    string json = @"{""Name"":{""id"":10,""name"":""Name"",""revisionDate"":1390293827000}}";
    var output = JsonConvert.DeserializeObject<Test>(json);
    lblOutput.Text = output.name;
}

This is intended to output the name property of the string json. However, it returns nothing.

2 Answers 2

9

The JSON you posted can be deserialized into an object which has a Name propery of type Test, not into a Test instance.

This

string json = @"{""id"":10,""name"":""Name"",""revisionDate"":1390293827000}";

would be a representation of a Test instance.

Your JSON may be deserialized into something like this:

public class Test
{
   public int id { get; set; }
   public string name { get; set; }
   public long revisionDate { get; set; }
}

public class Foo
{
    public Test Name { get; set; }
}

// ...


var output = JsonConvert.DeserializeObject<Foo>(json);
lblOutput.Text = output.Name.name;
1
  • 2
    Adding to this, it sometimes helps to drop your JSON into a visualizer tool to see these sorts of things jump out at you: jsoneditoronline.org
    – theMayer
    Jan 22, 2014 at 12:07
0

Valid json for Test class is below

{ "Name": { "id": 10, "name": "Name", "revisionDate": 1390293827000 } }

and Also your json is in containg more data then only test class so you can also use like

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

Test oputput=dictionary["Name"];  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.