如何在属性名称中使用空格反序列化JSON

如何在属性名称中使用空格反序列化JSON

本文介绍了如何在属性名称中使用空格反序列化JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要反序列化的字符串数组.本质上,它只是对象列表.请注意,属性名称中带有空格:

I have a string array that I want to deserialize. Essentially, it is just a list of objects. Note that the attributes have spaces in the names:

[    {        \"Event Name\": \"Hurricane Irma PR\",        \"Storm Start (LST)\": \"2017-08-30\",        \"Storm End (LST)\": \"2017-09-13\",        \"Grid Cell Number\": 16412,        \"Grid Cell State\": \"PR\",        \"Grid Cell Name\": \"Grid26_0\", ...

我创建了一个公共类以根据想要的特定属性(我不想要所有数据)来对字符串进行模板化,但是我不确定如何处理名称中的空格我想要的属性.

I created a public class to template the string based on specific attributes that I want ( I don't want all the data) but I am not sure how to handle for the spaces in the names of the attributes that I want.

    public class New_Events_Dataset
    {
        public string EventName { get; set; }
        public string StormStart { get; set; }
        public string StormEnd { get; set; }
        public string GridCellState { get; set; }
        public string GridCellName { get; set; }
        public string USGSGageSiteNo { get; set; }
        public string ReturnPeriodatGridCell { get; set; }
    }

当我在类 New_Events_Dataset 中应用反序列化器时,如下所示:

When I apply the deserializer with my class New_Events_Dataset like this:

    var jsonResponse = returnJson.Deserialize<List<New_Events_Dataset>>(strresult);
    string json = new JavaScriptSerializer().Serialize(jsonResponse);
                return json;

我最终返回了类似的内容.我在做什么错了?

I end up returning something like this. What am I doing wrong?

[{"EventName":null,"StormStart":null,"StormEnd":null,"GridCellState":null,"GridCellName":null,"USGSGageSiteNo":null,"ReturnPeriodatGridCell":null}

推荐答案

不幸的是,键必须彼此完全匹配.
解决问题的最佳方法之一是为每个属性定义JsonProperty属性,以正确获取反序列化的对象.您可以使用它来指定属性的json键名.
您可以看一下这个问题,它的答案可以帮助您更好地理解: JsonProperty的示例

Unfortunately keys must match exactly each other.
One of the best ways to solve your problem is to define JsonProperty attribute for each property to get Deserialized object correctly. You can specify property's json key name with it.
You can take a look to this question and it's answer for better understanding:An example of JsonProperty

修改:
如评论中所述,因为您正在使用 JavaScriptSerializer JsonPropertyAttribute 在这种情况下不起作用.但是您可以通过添加 Newtonsoft.Json Nuget Package并使用它来对它进行反消毒来使用它方式:


As in comments mentioned, because you are using JavaScriptSerializer JsonPropertyAttribute doesn't work in this situation.But you can use it by adding Newtonsoft.Json Nuget Package and using it's deserilizer this way:

JsonConvert.DeserializeObject<AzureResourceData>(jsonString);

这篇关于如何在属性名称中使用空格反序列化JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:13