c# - 如何反序列化没有名称的 JSON 数组?

标签 c# .net json mono json-deserialization

我不知道如何编写一个类来反序列化 .Net 中 JSON 中的对象列表。

从 JSON 规范中,我们了解到这是有效的 JSON:

   [
      {
         "precision": "zip",
         "Latitude":  37.7668,
         "Longitude": -122.3959,
         "Address":   "",
         "City":      "SAN FRANCISCO",
         "State":     "CA",
         "Zip":       "94107",
         "Country":   "US"
      },
      {
         "precision": "zip",
         "Latitude":  37.371991,
         "Longitude": -122.026020,
         "Address":   "",
         "City":      "SUNNYVALE",
         "State":     "CA",
         "Zip":       "94085",
         "Country":   "US"
      }    ]

所以我构建了这个类来处理反序列化:

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace JsonRfc{

[Serializable]
public class Location {

    public string Precision;
    public double Latitude;
    public double Longitude;
    public string Address;
    public string City;
    public string State;
    public string Zip;
    public string Country;

    public Location(){}

    public static Location DeserializedJson(string responseJson)
    {
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        return jsSerializer.Deserialize<Location>(responseJson);
    }
}

[Serializable]
public class Locations {

    public List<Location> Location;

    public Locations(){}

    public static Locations DeserializedJson(string responseJson)
    {
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        return jsSerializer.Deserialize<Locations>(responseJson);
    }
}
}

尽管已将有效的 Json 传递给方法,但反序列化的对象为 null。

我尝试过但失败的其他事情包括:使 Locations 成为数组而不是列表(因此:public Location[] Location; ),以及反序列化到位置,即使 Json 包含位置数组也是如此。

那么,.Net 开发人员应该如何反序列化对象数组?我希望上面的方法有效,但没有。

最佳答案

只返回一个数组

var locs = Location.DeserializedJson(json);

public class Location
{

    public string Precision;
    public double Latitude;
    public double Longitude;
    public string Address;
    public string City;
    public string State;
    public string Zip;
    public string Country;

    public static Location[] DeserializedJson(string responseJson)
    {
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        return jsSerializer.Deserialize<Location[]>(responseJson);
    }
}

PS:请注意 [Serializable] 是不必要的。

关于c# - 如何反序列化没有名称的 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18345152/

相关文章:

c# - 如何使用 Regex 只允许逗号分隔列表中单个值的特定长度?

c# - 将字节数组作为新程序执行

json - 如何使用 JSONDecoder 解码未知类型的 JSON?

javascript - 是否可以在不使用索引号的情况下访问 json 数组元素?

javascript - 将 JSON 映射到对象

c# - xUnit测试asp net core Mapper未初始化

c# - 为什么 List<double> 类型会以这种方式表现?

c# - 无法检索项目元数据。确保这是一个基于MSBuild的.NET Core项目。 (迁移)

.net - 对 TLS 1.1 和 1.2 的 Windows 紧凑框架支持

c# - 将 HttpConfigurationExtensions 添加到 ASP.NET 项目