How to deserialize JSON with unnamed collection of types using DataContractSerializer

前端 未结 2 561
-上瘾入骨i
-上瘾入骨i 2020-12-21 07:27

I\'m using web service to get data about route mileage. Then I\'m using deserializer to parse it out. Here is how JSON looks:

[{\"__type\":\"CalculateMilesRe         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-21 08:06

    About making the __type attribute disappear there are discussions on SO.

    Here is one, which solved in the following way:

    change the WebMethod return type to object, i.e.

    [WebMethod]
    public static object ApplyCredits(int addonid, int[] vehicleIds) 
    

    instead of

    [WebMethod]
    public static WebMethodReturn ApplyCredits(int addonid, int[] veh
    

    Another one solved by

    Adding the namespace parameter [DataContract(Namespace = "")] to the data contract.

    I'm not sure how to write object to properly parse it

    Based on the response you can build classes in which your JSON is going to fit, but since you have the model classes you are supposed to use the same from which your JSON was built. Maybe I didn't get here something correctly from your question.

    Here is a crafted model example in which your JSON would fit in:

    public class ResultType
    {
        public string RouteID { get; set; }
        public List Points { get; set; }
        public double TMiles { get; set; }
    
        public ResultType()
        {
            RouteID = "";
            Points = new List();
            TMiles = 0;
        }
    }
    
    public class GeoTunnelPoints
    {
        double Lat { get; set; }
        double Lon { get; set; }
    
        public GeoTunnelPoints()
        {
            Lat = 0.0;
            Lon = 0.0;
        }
    }
    

    Example usage:

    // Your example JSON after excluding the __type
    string input = 
                    "[" +
                        "{" + 
                           "\"RouteID\":null, " +
                            "\"TMiles\":445.5}," +
                        "{" +
                            "\"RouteID\":null," +
                            "\"GeoTunnelPoints\":" +
                                  "[" +
                                      "{\"Lat\":\"34.730466\",\"Lon\":\"-92.247147\"}," +
                                      "{\"Lat\":\"34.704863\",\"Lon\":\"-92.29329\"}," +
                                      "{\"Lat\":\"34.676312\",\"Lon\":\"-92.364654\"}," +
                                      "{\"Lat\":\"29.664271\",\"Lon\":\"-95.236735\"}" +
                                  "]" +
                        "} " +
                    "]";
    
    List resultList = new List();
    // This will be your C# result collection
    resultList = new JavaScriptSerializer().Deserialize>(input);
    

提交回复
热议问题