解析 JSON 响应,其中对象以 C# 中的数字开头 [英] Parse JSON response where the object starts with a number in c#

查看:57
本文介绍了解析 JSON 响应,其中对象以 C# 中的数字开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将来自 REST 服务的响应反序列化为 C# 强类型类 - 但是我在这篇文章中遇到了同样的问题:如何输出键以数字开头的 JSON 值?

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?

但是我有一个问题,你不能在 c# 中用数字开头变量名 - 这意味着该级别的类只是反序列化为 null.

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.

我需要知道如何进入对象并将它们反序列化为 c# 类.

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

我当前的代码如下:

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;
            }
        }
    }

我无法改变服务推回数据的方式

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

推荐答案

处理这个问题的正确方法是在目标类上使用 JsonProperty 标签来定义要监听的 Json 属性,如下所示(引用自 https://stackoverflow.com/questions/24218536/deserialize-json-that-has-some-property-name-starting-with-a-number

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; }
    ...

感谢@HebeleHododo 的评论回答

Thanks to @HebeleHododo for the comment answer

这篇关于解析 JSON 响应,其中对象以 C# 中的数字开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆