user7399041
user7399041

Reputation: 137

Issue with JSON parse

I'm storing JSON data into class. However, I'm having difficult time solving the second JSON line below, BadGuy. I cannot store it's data correctly.

{
     \"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; }
}

How I deserialize my JSON:

var ser = JsonConvert.DeserializeObject<ClsResult>(myJSON);

Upvotes: 0

Views: 60

Answers (1)

Andrew Skirrow
Andrew Skirrow

Reputation: 3451

Have you tried this? BadGuy is a string so you should define it as such.

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

Upvotes: 5

Related Questions