Eritey
Eritey

Reputation: 143

Parsing a JSON structure to an object but the structure could contain different names

I need to be able to access the code and title properties of each shipping service but the object they're contained in is named differently each time and I don't have control of this.

JSON file

Upvotes: 1

Views: 569

Answers (3)

Nguyen Kien
Nguyen Kien

Reputation: 1927

The code below use with json.net.

///Custom converter to parse the container.
public class ItemConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var jobj = JObject.Load(reader);

        var item = jobj.First.First.ToObject<Item>();
        var container = new ItemContainer
        {
            Name = jobj.First.Path,
            Data = item
        };
        return container;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof (Item);
    }
}

[JsonConverter(typeof(ItemConverter))]
public class ItemContainer
{
    public string Name { get; set; }

    //Your object is here
    public Item Data { get; set; }
}

public class Item
{
    public string code { get; set; }
    //Other properties
}

public class RootObj
{
    public ItemContainer[] ShippingMethods { get; set; }
}

Deserialize json:

JsonConvert.DeserializeObject<RootObj>("Your json string");

Upvotes: 1

Ruchir Shah
Ruchir Shah

Reputation: 316

You can parse your JSON object direct to model using Newtonsoft.Json nuget package.

var objData = JsonConvert.DeserializeObject<MyData>(jsonString);

You can get your model class from json data from http://json2csharp.com/

You can convert using dynamic object as well

var objData = JsonConvert.DeserializeObject<dynamic>(jsonString); 

Or without specifying model calss

var objData = JsonConvert.DeserializeObject(jsonString);

Upvotes: 2

Mohammed Swillam
Mohammed Swillam

Reputation: 9242

you can use Json.net to deserialize your json into a dynamicvariable to fix the (unknown properties) issue, and access your properties by name assuming you know them.

example:

dynamic parsedObject = JsonConvert.DeserializeObject("{\"id\":\"123\"}");
parsedObject.id // it should read 123

Upvotes: 1

Related Questions