如何反序列化没有名称的JSON数组
本文关键字:JSON 数组 有名称 反序列化 | 更新日期: 2023-09-27 18:28:27
我不知道如何编写一个类来反序列化.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);
}
}
}
反序列化的对象为null,尽管已将有效的Json传递给该方法。
我尝试过的其他失败的事情包括:使Locations成为一个数组而不是一个列表(so:public Location[]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]
s是不必要的