9

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;
Sign up to request clarification or add additional context in comments.

1 Comment

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
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"];  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.