2

I need to deserialize the following:

{"result":{"success":true,"value":"8cb2237d0679ca88db6464eac60da96345513964"}}

to a C# object using Newtonsoft.Json

WebClient wc = new WebClient();
var json = wc.DownloadString(url);
Worker w = JsonConvert.DeserializeObject<Worker>(json);

Here is the class code:

public class Worker
{

    [JsonProperty("success")]
    public string success { get; set; }

    [JsonProperty("value")]
    public string value { get; set; }
}

The code does not error out, but the success and value are null.

0

3 Answers 3

5

You're missing the outer object.

public class Worker
{
     [JsonProperty("result")]
     public Result Result { get; set; }
}

public class Result
{
    [JsonProperty("success")]
    public string Success { get; set; }

    [JsonProperty("value")]
    public string Value { get; set; }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks! Figured "result" needed to be serialized.
Also you may want to consider capitalizing your property names, since that is the standard convention in C#. Since you're already controlling the JSON serialization with attributes, it won't affect that. I edited my answer to show what I mean.
@luksan +1 What if I want the C# class to contain three fields: Result, Success and Value? When I set the JsonProperty attribute to "result.success" or "result.value" it returns null. Is it possible?
@Anar I'm not sure I understand. Maybe try creating a new question on here with example code.
My fault, sorry. I wanted to ask whether you could specify JsonProperty value two levels deep, hence, "result.success". It does not work that way, maybe you know a way.
|
0

You don't need any class and can make use of dynamic keyword

string json = @"{""result"":{""success"":true,""value"":""8cb2237d0679ca88db6464eac60da96345513964""}}";

dynamic dynObj = JsonConvert.DeserializeObject(json);
Console.WriteLine("{0} {1}", dynObj.result.success, dynObj.result.value);

Comments

0

I'm not familiar with that library, but success and result look to be both properties of the object "result"

Have you tried [JsonProperty("result.success")]?

Edit: Well, regardless it looks like a scoping issue. After viewing the documentation, this is my new suggestion:

public class Result{
 [JsonProperty("result")]
 public Worker result { get; set; }
}

then Json.Convert.Deserialize<Result>(json) instead.

1 Comment

Good thought... still Null.

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.