1

I'm trying to deserialise a response from a REST service into C# Strongly typed classes - however I've ran into the same issue has in this post: How do I output this JSON value where the key starts with a number?

However I have the issue that you cannot start a variable name in c# with a number - meaning that the class at that level just deserialises into null.

I need to know how to get into the objects and deserialise them into the c# classes.

My Current code is below:

public static async Task<T> MakeAPIGetRequest<T>(string uri)
    {
        Uri requestURI = new Uri(uri);
        using (HttpClient client = new HttpClient())
        {
            HttpResponseMessage responseGet = await client.GetAsync(requestURI);
            if (responseGet.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception(String.Format(
                "Server error (HTTP {0}: {1}).",
                responseGet.StatusCode,
                responseGet.Content));
            }
            else
            { 
            string response = await responseGet.Content.ReadAsStringAsync();
                T objects = (JsonConvert.DeserializeObject<T>(response));

                return objects;
            }
        }
    }

EDIT: I cannot change the way the service is pushing the data back

Community
  • 1
  • 1
Jared Kove
  • 235
  • 1
  • 13

2 Answers2

2

The correct way to deal with this was to use the JsonProperty tag on the target classes to define what Json property to listen for, as shown below (referenced from https://stackoverflow.com/questions/24218536/deserialize-json-that-has-some-property-name-starting-with-a-number

public class MyClass
{
    [JsonProperty(PropertyName = "24hhigh")]
    public string Highest { get; set; }
    ...

Thanks to @HebeleHododo for the comment answer

Community
  • 1
  • 1
Jared Kove
  • 235
  • 1
  • 13
  • how are you gonna do it for `[{'1':{'name':'test','age':'test'}},{'2':{'name':'another','age':'another'}}]` – Amit Kumar Ghosh Nov 24 '16 at 12:08
  • @AmitKumarGhosh you would put "1" in the property name, or if its a variable amount of items you would use a for loop using your method. – Jared Kove Nov 24 '16 at 13:50
0

While there is no direct way to construct a strongly typed C# object in this case, You could still have the capabilities to parse the json string manually and extract values -

var json = "{'1':{'name':'test','age':'test'}}";
var t = JObject.Parse(json)["1"];
Console.WriteLine(t["name"]); //test
Console.WriteLine(t["age"]);  //test
Amit Kumar Ghosh
  • 3,618
  • 1
  • 20
  • 24
  • Thanks for your response - this was how i was going to approach it until i saw: http://stackoverflow.com/questions/24218536/deserialize-json-that-has-some-property-name-starting-with-a-number which makes it possible. – Jared Kove Nov 24 '16 at 11:58