I have a json string that looks like this:
{\"StatusCode\":\"200\",\"ResponseMessage\":\"Success\",\"Payload\":{\"Address\":\"1 Main St.\",\"City\":\"Anytown\"}}
I would like NewtonSoft.json to parse it into the following class:
public partial class HttpGetResponse
{
[JsonProperty("StatusCode")]
public string StatusCode { get; set; }
[JsonProperty("ResponseMessage")]
public string ResponseMessage { get; set; }
[JsonProperty("Payload")]
public string Payload { get; set; }
}
Unfortunately, I can't get the NewtonSoft.json code to treat the third element ("Payload") as just a string. It want's to parse it out as json.
Any suggestions on how to do this?
Or, am I wrong in using Newtonsoft.json to do this? I WILL be using it to parse out the payload at a later point in my program.
答案 0 :(得分:0)
Payload:{
"Address":"1 Main St.",
"City":"Anytown"
}
As you see Payload
should be a complex object instead of string
. So, change your model classes.
public class Payload
{
public string Address { get; set; }
public string City { get; set; }
}
public class HttpGetResponse
{
public string StatusCode { get; set; }
public string ResponseMessage { get; set; }
public Payload Payload { get; set; }
}
答案 1 :(得分:0)
classes;
public partial class HttpGetResponse
{
[JsonProperty("StatusCode")]
public string StatusCode { get; set; }
[JsonProperty("ResponseMessage")]
public string ResponseMessage { get; set; }
[JsonProperty("Payload")]
public Payload Payload { get; set; }
}
public class Payload
{
public string Address { get; set; }
public string City { get; set; }
}
Converts;
string w1 = "{\"StatusCode\":\"200\",\"ResponseMessage\":\"Success\",\"Payload\":{\"Address\":\"1 Main St.\",\"City\":\"Anytown\"}}";
HttpGetResponse w2= JsonConvert.DeserializeObject<HttpGetResponse>(w1);
答案 2 :(得分:0)
I think you just want to parse out the common parts of this json object and payload varies from message to message. So do it like this (it means you dont have to define a class with 'payload' in it)
dynamic parsed = JsonConvert.Deserialize<dynamic>(str);
var StatusCode = parsed.StatusCode;
...
If I misundertood and you actually want to extract the payload then thats different. THis code does not present you with a string for payload.