2017-04-09 35 views
0

我有设置了这样的类的集合:JSON不按预期反序列化?

public class Xml 
{ 
    public string version { get; set; } 
    public string encoding { get; set; } 
} 

public class Content 
{ 
    public string Expires { get; set; } 
    public string MaxArrivalScope { get; set; } 
} 

public class Trip 
{ 
    public string ETA { get; set; } 
    public string TripNo { get; set; } 
    public string WheelchairAccess { get; set; } 
} 

public class Destination 
{ 
    public string Name { get; set; } 
    public List<Trip> Trip { get; set; } 
} 

public class Route 
{ 
    public string RouteNo { get; set; } 
    public string Name { get; set; } 
    public Destination Destination { get; set; } 
} 

public class Platform 
{ 
    public string PlatformTag { get; set; } 
    public string Name { get; set; } 
    public Route Route { get; set; } 
} 

public class JPRoutePositionET 
{ 
    public string xmlns { get; set; } 
    public string xsi { get; set; } 
    public string schemaLocation { get; set; } 
    public Content Content { get; set; } 
    public Platform Platform { get; set; } 
} 

public class RootObject 
{ 
    public Xml xml { get; set; } 
    public JPRoutePositionET JPRoutePositionET { get; set; } 
} 

}

我有JSON是这样的:

{ 
    "xml": { 
    "version": "1.0", 
    "encoding": "utf-8" 
    }, 
    "JPRoutePositionET": { 
    "xmlns": "urn:connexionz-co-nz:jp", 
    "xsi": "http://www.w3.org/2001/XMLSchema-instance", 
    "schemaLocation": "urn:connexionz-co-nz:jp JourneyPlanner.xsd", 
    "Content": { 
     "Expires": "2017-04-09T15:59:31+12:00", 
     "MaxArrivalScope": "60" 
    }, 
    "Platform": { 
     "PlatformTag": "2628", 
     "Name": "Awatea Rd near Awatea Gdns", 
     "Route": { 
     "RouteNo": "125", 
     "Name": "Redwood/Westlake", 
     "Destination": { 
      "Name": "Westlake & Halswell", 
      "Trip": [ 
      { 
       "ETA": "4", 
       "TripNo": "4751", 
       "WheelchairAccess": "true" 
      }, 
      { 
       "ETA": "32", 
       "TripNo": "4752", 
       "WheelchairAccess": "true" 
      } 
      ] 
     } 
     } 
    } 
    } 
} 

为什么Newtonsoft不能正确解析到Platform类?它返回null。我是否需要格式化JSON以删除我不想要的所有其他信息?或者是我缺少的东西?

+0

我不确定这是否有效:'公开列表 Trip'。试用'public Trip [] Trip' –

+0

你的对象嵌套在json对象中。你需要把对象拉出来,然后将它们反序列化到合适的类。你能发布反序列化的代码部分吗? –

+0

@MariaInesParnisari我正在使用NewtonSoft反序列化到列表所以它应该像那样工作。 –

回答

0

法比奥的的

var result = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(js‌​onString);

曾任职评论。

但是现在当我得到像pastebin.com/pebp178s这样的JSON时,我似乎无法使用Json2CSharp获取我需要的类,因为它不会使Destination成为List,它也会将Trip改为对象一类。这真的很奇怪。它只是抛出一个错误,说JSON不能被解析。