3

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?

1
  • Was my update useful? Commented Jun 26, 2015 at 12:43

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I tried your suggestion but I still have problems with parsing Properties. I then tried a custom converter but no luck. I just added the an Update. Do you know what might be going wrong?
Miguel, I'm trying it here, I'll post an answer soon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.