2

私は成功せずに逆シリアル化しようとしているこの特定の JSON 応答を持っています。誰かが私を助けてくれることを願っています。

これが私が得るJSON応答です:

{
"num_locations": 1,
"locations": {
    "98765": {
        "street1": "123 Fake Street",
        "street2": "",
        "city": "Lawrence",
        "state": "Kansas",
        "postal_code": "66044",
        "s_status": "20",
        "system_state": "Off"
    }
}

}

json2csharp http://json2csharp.comを使用して、これらの推奨クラスを取得しました。

    public class __invalid_type__98765
    {
        public string street1 { get; set; }
        public string street2 { get; set; }
        public string city { get; set; }
        public string state { get; set; }
        public string postal_code { get; set; }
        public string s_status { get; set; }
        public string system_state { get; set; }
    }

    public class Locations
    {
        public __invalid_type__98765 __invalid_name__98765 { get; set; }
    }

    public class RootObject
    {
        public int num_locations { get; set; }
        public Locations locations { get; set; }
    }

しかし、コードでそれを使用しようとすると:

var locationResponse = JsonConvert.DeserializeObject<RootObject>(response.Content);

私が得るものは(時計)です:

locationResponse : {RestSharpConsoleApplication.Program.RootObject} : RestSharpConsoleApplication.Program.RootObject
locations : {RestSharpConsoleApplication.Program.Locations} : RestSharpConsoleApplication.Program.Locations
__invalid_name__98765 : null : RestSharpConsoleApplication.Program.__invalid_type__98765
num_locations : 1 : int

明らかに、私は DeserializeObject の適切なクラス (json2csharp) を作成していません。悲しいことに、JSON 応答 (vendor = SimpliSafe) を制御することはできません。

「98765」が値 (ロケーション番号) であることは明らかですが、json2csharp はそれをこの __invalid_type__98765 クラスにします。これがおそらく null になる理由です。

この特定の JSON を正常に逆シリアル化するには、クラスがどのように検索すればよいでしょうか?

ありがとう!ザックス

4

3 に答える 3

3

辞書でこれを行うことができるはずです:

public class MyData{ 
  [JsonProperty("locations")]
  public Dictionary<string, Location> Locations {get;set;} 
}
public class Location
{
  public string street1 { get; set; }
  public string street2 { get; set; }
  public string city { get; set; }
  public string state { get; set; }
  public string postal_code { get; set; }
  public string s_status { get; set; }
  public string system_state { get; set; }
}
于 2015-03-31T19:10:29.503 に答える
-2

これを回避するために使用する属性を介してプロパティ名を指定することもできます。

public class RootObject
{
    public int num_locations { get; set; }
    public Locations locations { get; set; }
}

public class Locations
{
    [JsonProperty("98765")]
    public LocationInner Inner { get; set; }
}

public class LocationInner
{
    public string street1 { get; set; }
    public string street2 { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    public string postal_code { get; set; }
    public string s_status { get; set; }
    public string system_state { get; set; }
}

...しかし、場所が実際には場所オブジェクトの配列になるように、JSON が適切にフォーマットされていれば、本当に良いでしょう。

于 2015-03-31T19:16:31.473 に答える