coldzero
coldzero

Reputation: 25

Deserialize json object xamarin android c#

I have little issue with deserialize json object. My json from http url:

Screen of my downloaded JSON

I don't know how to deserialize to make dynamically creating buttons. I figure out how to create buttons with text, but I don't know how to make them with options that they have. I try to get these options in Windows Form app for test, but app will crash. Thank you for help.

Upvotes: 2

Views: 13408

Answers (2)

Henrique Forlani
Henrique Forlani

Reputation: 1353

Your classes should be something like:

public class Type
{
    public int id { get; set; }
    public string name { get; set; }
    public bool closedQuestion { get; set; }
    public bool multiAnswer {get; set;}
    public bool usesImage {get; set; }
}
public class RootObject
{
    public int id { get; set; }
    public string name { get; set; }
    public Type type { get; set; }
    public List<string> options { get; set; }
}

Then you should be able to deserialize your json, using Newtonsoft.Json:

List<RootObject> myData = JsonConvert.DeserializeObject<List<RootObject>>(json);

Upvotes: 3

Nick Bull
Nick Bull

Reputation: 9876

Using Newtonsoft.NET:

var obj = JsonConvert.DeserializeObject(json);

You can also make a pairing class and use generics:

public JsonClass {
    // Do this for each property you want to map.
    [JsonProperty(PropertyName="id")]
    public int Id { get; set; }

    [JsonProperty(PropertyName="name")]
    public int Name { get; set; }

    [JsonProperty(PropertyName="type")]
    public MessageType Message { get; set; }
}

public class MessageType {
    [JsonProperty(PropertyName="id")]
    public int Id { get; set; }
    // etc...
}

then do:

JsonClass obj = JsonConvert.DeserializeObject<JsonClass>(json);
MessageType messageType = obj.Message;

Upvotes: 3

Related Questions