2

How to deserialize the web response like this:

[{"_exp":"2014-06-05T23:58:03.859Z","_id":"123","$val":"dabg"}, 
{"_exp":"2014-07-05T23:58:03.859Z","_id":"143","$val":"dabg"}]

Here my specific question is that I am not able to create a response class having the variable name starting with $ as C# does not support this type of naming convention...

dbc
  • 104,963
  • 20
  • 228
  • 340
user3904654
  • 133
  • 1
  • 1
  • 5

2 Answers2

2

You could manually deserialize into your model class, allowing you to rename the json properties into valid C# properties. Here is an example using JSON.NET.

List<Model> list = new List<Model>();

JArray array = JArray.Parse(json);
foreach (JObject item in array)
{
    list.Add(new Model() {
        Exp = item.Value<DateTime>("_exp"),
        Id = item.Value<int>("_id"),
        Val = item.Value<string>("$val")
    });
}

public class Model
{
    public DateTime Exp { get; set; }
    public int Id { get; set; }
    public string Val { get; set ;}
}

Another alternative would be replacing $val with _val. Property names can start with _ so the other two are valid. This would allow a automatic deserializing into a model. The added quotes and colon would allow it to only target the property names "$val": so that you don't accidentally replace a property value.

string newJson = json.Replace("\"$val\":", "\"_val\":");
Model[] models = JsonConvert.Deserialize<Model[]>(newJson);

public class Model
{
    public string _val { get; set; }
    public DateTime _exp { get; set; }
    public int _id { get; set; }
}
Despertar
  • 21,627
  • 11
  • 81
  • 79
0

Return an array or collection of Dictionary<string, object>. You can use whatever you want as the key values and it will serialize/deserialize as you want

Robert Levy
  • 28,747
  • 6
  • 62
  • 94