I am curenntly making an thunder storm app for windows phone but i have a problem.
When i have converted the JSON string to C# classes i have seen that the class names just contain numbers.
How can i deserialize the JSON String?
public class 904
{
public string id { get; set; }
public string name { get; set; }
public string name_url { get; set; }
public string region_path { get; set; }
}
public class Result
{
public 904 904 { get; set; }
}
public class RootObject
{
public bool status { get; set; }
public Result result { get; set; }
public int time_valid_to { get; set; }
}
The JSON string
{"status":true,"result":{"904":{"id":"904","name":"Wien Alsergrund","name_url":"wien_alsergrund","region_path":"oesterreich\/wien\/wien_alsergrund"}},"time_valid_to":1424978715}
It looks like the result
property is effectively a map of results - so you can represent that with a Dictionary<,>
. This works:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
public class ResultEntry
{
public string id { get; set; }
public string name { get; set; }
public string name_url { get; set; }
public string region_path { get; set; }
}
public class RootObject
{
public bool status { get; set; }
public Dictionary<int, ResultEntry> result { get; set; }
public int time_valid_to { get; set; }
}
class Test
{
static void Main()
{
string json = File.ReadAllText("json.txt");
var root = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(root.result[904].name);
}
}
I'd strongly recommend using cleaner property names and specifying attributes to tell Json.NET how to map them to JSON though.
See more on this question at Stackoverflow