0

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}
  • What is the original Class name perhaps from that we can deduce what is happening – Blaatz0r Mar 05 '15 at 09:23
  • You cannot have class name that is a number – Nikola Sivkov Mar 05 '15 at 09:24
  • You cannot use number at start of the name of a class, add `_` symbol, for example. – FLCL Mar 05 '15 at 09:24
  • @Aviatrix The object has been serialized to json at a certain time. this means that either the classname was a number which should be impossible or the classname has been tampered with. In both cases i think he already knows that the classname shouldn't be a number. – Blaatz0r Mar 05 '15 at 09:28
  • The original class names are like up there. Just RootObject was generated by the generator. When i add an `_` the deserializiation wouldn't work! – Peter Weilharter Mar 05 '15 at 09:29

1 Answers1

2

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194