2017-04-09 37 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不能被解析。