Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom JSon convertion to C# objects

Tags:

json

c#

json.net

I am getting JSon from a third party API which does not match my classes.

Some JSon properties are not be be converted others has different names, etc.

How can I define a custom conversion from the JSON to my C# object.

These are the objects I have in C#:

public class PropertyList {
  public Int32 Page { get; set; }
  public String[] ErrorMessages { get; set; }
  public List<Property> Properties { get; set; }
}

public class Property {
  public String Name { get; set; }
  public String Reference { get; set; }
  public String Region { get; set; }
  public IList<String> Features { get; set; }
  public String Id { get; set; }
  public Double Price { get; set; }
  public IList<String> ImagesUrls { get; set; }
}

And this is the JSon data which I want to convert from:

{
  "page" : 0,
  "errorMessages" : [ ],
  "listings" : [ 
    {
      "data" : {
        "name" : "The name",
        "reference__c" : "ref1234",
        "region__c" : "London",
        "features__c" : "Garage;Garden;",
        "id" : "id1234",
        "price_pb__c" : 700000,
      },
      "media" : {
        "images" : [ 
          {
            "title" : "image1",
            "url" : "http://www.domain.com/image1"
          }, 
          {
            "title" : "image2",
            "url" : "http://www.domain.com/image2"
          }
        ]
      }
    }
    {
      NOTE: Other items
    }
  ]
}

How should I do this?

UPDATE 1

Using Thiago suggestion I was able to parse Page and ErrorMessages but not Properties. So I create the following converter:

public class PropertyResultConverter : JsonConverter {

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

  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {

    JObject jo = JObject.Load(reader);
    PropertyResult propertyResult = jo.ToObject<PropertyResult>();
    propertyResult.Properties = jo.SelectToken("listings.data").ToObject<List<Property>>();
    return propertyResult;

  }

  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
    throw new NotImplementedException();
  }

}

But when I try this I get the following error: An exception of type 'System.NullReferenceException' occurred

On:

propertyResult.Properties = jo.SelectToken("listings.data").ToObject<List<Property>>();

Any idea why this happens?

like image 834
Miguel Moura Avatar asked Sep 14 '26 15:09

Miguel Moura


1 Answers

Miguel, have you tried http://www.newtonsoft.com/json ?

You can do the mappings of your code using C# attributes, like the snippets below.

public class PropertyList {
  [JsonProperty("page")]
  public Int32 Page { get; set; }
  [JsonProperty("errorMessages")]
   public String[] ErrorMessages { get; set; }
  [JsonProperty("listings")]
   public List<Property> Properties { get; set; }
}
public class Property {
  [JsonProperty("name")]
  public String Name { get; set; }
  [JsonProperty("reference__c")]
  public String Reference { get; set; }
  [JsonProperty("region__c")]
  public String Region { get; set; }
  [JsonProperty("features__c")]
  public IList<String> Features { get; set; }
  [JsonProperty("id")]
  public String Id { get; set; }
  [JsonProperty("price_pb__c")]
  public Double Price { get; set; }
  [JsonProperty("media")]
  public IList<String> ImagesUrls { get; set; }
}

I'm not sure if IList will work as you are expecting. I believe you will need to adapt it to Dictionary.

You can take a look on the API: http://www.newtonsoft.com/json/help/html/SerializationAttributes.htm

UPDATE

Try to parse 'data' using the snippet below:

JObject jsonObject = JObject.Parse(json);
            IList<JToken> results = jsonObject["listings"]["data"].Children().ToList();

            IList<Property> processedList = new List<Property>();
            foreach (JToken item in results)
            {
                Property propertyItem = JsonConvert.DeserializeObject<Property>(item.ToString());
                processedList.Add(propertyItem);
            }

I ran that snippet and it worked. You can explore the code that I generated on my github:

https://github.com/thiagoavelino/VisualStudio_C/blob/master/VisualStudio_C/StackOverFlow/ParsingJason/ParsingJson.cs

like image 81
Thiago Avelino Avatar answered Sep 16 '26 04:09

Thiago Avelino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!