我将JSON
数据存储到课程中。但是,我很难解决下面的第JSON
行,BadGuy
。我无法正确存储数据。
{
\"First\":{\"FirstBool\":1, \"aString\":\"hello\"},
\"BadGuy\":\"BadGuy says hello\" //<--- this one, how do I tackle this in code below?
}
public class First
{
[JsonProperty("FirstBool")]
public int FirstBool { get; set; }
[JsonProperty("aString")]
public string aString { get; set; }
}
public class BadGuy //my poorly attempt
{
[JsonProperty("BadGuy")]
public string BadGuy { get; set; }
}
public class ClsResult
{
[JsonProperty("First")]
public First First { get; set; }
[JsonProperty("BadGuy")] // another poorly attempt
public BadGuy BadGuy { get; set; }
}
我如何反序列化JSON
:
var ser = JsonConvert.DeserializeObject<ClsResult>(myJSON);
答案 0 :(得分:5)
BadGuy
是一个字符串,因此您应该将其定义为。
public class First
{
[JsonProperty("FirstBool")]
public int FirstBool { get; set; }
[JsonProperty("aString")]
public string aString { get; set; }
}
public class ClsResult
{
[JsonProperty("First")]
public First First { get; set; }
[JsonProperty("BadGuy")]
public string BadGuy { get; set; }
}
public static class Program
{
public static void Main()
{
string json = GetJson();
ClsResult result = JsonConvert.DeserializeObject<ClsResult>(myJSON);
Console.WriteLine("Bad Guy == " + result.BadGuy);
}
}