How to deserialize a JSON array with no name?

2019-07-14 12:57发布

问题:

I cannot figure out how to write a class for deserializing a list of objects from JSON in .Net.

From the JSON spec, we learn that this is valid 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"
      }    ]

So I constructed this class to handle deserialization:

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

The deserialized object is null despite having valid Json passed to the method.

Other things I tried that failed included: making Locations an array instead of a list (so: public Location[] Location; ), and deserializing to location even though the Json contains an array of locations.

So, how is a .Net developer expected to deserialize an array of objects? I expected the above to work and it does not.

回答1:

Just return an array

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: note that [Serializable]s are unnecessary.