2013-08-23 30 views
1

让我们说我有这个类:是否有可能反序列化和序列化json对象在不同的​​主题名称?

public class Resource 
{ 
    [JsonProperty(propertyName: "address")] 
    public Domain.DTO.Address Addresses { get; set; } 
} 

JSON字符串值的样子:

{ 
    . 
    . 
    . 
    "resourceSets":[ 
    { 
     "estimatedTotal":1, 
     "resources":[ 
      { 
       . 
       . 
       . 
       "address":{ 
       "UserLocation":null, 
       "adminDistrict":"National Capital Region", 
       "adminDistrict2":"Third District NCR", 
       "locality":"Caloocan City", 
       "postalCode":null, 
       "addressLine":"Yellow Bell Ext", 
       "formattedAddress":"Yellow Bell Ext, Caloocan City, Philippines", 
       "neighborhood":"Barangay 161", 
       "landmark":null, 
       "countryRegion":"Philippines" 
       } 
      } 
     ] 
    } 
    ] 
} 

这正确反序列化。但是,当序列化Resource类时,我希望将某些属性(如“地址”)序列化为“地址”而不是“地址”。

我试过使用DataMember,但没有工作。任何想法?

+0

你想在反序列化时使用“地址”,但在序列化时使用“地址”吗? –

回答

3
[JsonProperty(propertyName: "address")] 

使其序列化为"address"

删除该属性,它将序列化为C#属性名称。

string json = Newtonsoft.Json.JsonConvert.SerializeObject(Class); 
+0

如果我这样做,它不会反序列化地址。 :) – fiberOptics

+2

它会。 'Newsonsoft.Json'忽略大小写。 –

+0

你是对的!谢谢!!!不知道。 :))顺便说一下,我将地址更改为地址,并且现在无需jsonProperty名称即可使用。 – fiberOptics