0

I'm currently trying to deserialize JSON strings returned from a web API using Json.NET. My problem is that in the response there are nested properties which always have the same structure (so generally should be deserialized to the same object type), but varying names. Here's a screenshot:

enter image description here

Is there any built in mechanism in Json.NET to handle these record objects? Otherwise, what would be the best way to handle this?

Thanks a lot!

japhwil
  • 299
  • 4
  • 16

2 Answers2

1
public class Records
{
    [JsonProperty(PropertyName = "records")]
    public List<int> records { get; set; }

    [JsonProperty("items")]
    private List<int> items { set { records.AddRange(value); } }
}

You could hack it by assigning other lists to the main one.

var str = "{\"records\":[\"1\",\"2\"],\"items\":[\"3\",\"4\"]}";
var json = JsonConvert.DeserializeObject<Records>(str);

After serializing it you'll get

{"records":[1,2,3,4]}
Ray Krungkaew
  • 6,652
  • 1
  • 17
  • 28
1

You could deserialize it to a Dictionary and then iterate over the keys.

(an example in this fiddle).

RMH
  • 817
  • 5
  • 13