Custom JSon transform for C # objects

I am getting JSon from 3rd party API that doesn't match my classes.

Some JSon properties don't translate, others have different names, etc.

How can I define a custom conversion from JSON for 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 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 it?

UPDATE 1

Using Thiago's suggestion, I was able to parse pages and errors, 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 to do this, I get the following error: Exception of type "System.NullReferenceException" was thrown

ABOUT:

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

      

Any idea why this is happening?

+3


source to share


1 answer


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

You can do mappings in your code using C # attributes like 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 expect. I believe you will need to adapt it to the dictionary.

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



UPDATE

Try to parse the "data" with 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 this snippet and it worked. You can examine the code I created on my github:

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

+1


source







All Articles