简体   繁体   中英

Deserialize JSON Object C# with Newtonsoft

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.

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; }
}

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM