JSON解析问题

时间:2017-01-11 10:47:41

标签: c# json

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

1 个答案:

答案 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);
    }
}