2017-09-26 114 views
0

我有一个类,看起来像在C#:序列化对象的一部分,JSON

public class MyClass 
{ 
    public string Id { get; set; } 
    public string Description { get; set; } 
    public string Location { get; set; } 
    public List<MyObject> MyObjectLists { get; set; } 
} 

,我只是想序列化JSON 一部分该对象的:刚刚标识说明位置属性,以便导致JSON看起来就像这样:

{ 
    "Id": "theID", 
    "Description": "the description", 
    "Location": "the location" 
} 

是否有如何做到这一点?

回答

1

如果您正在使用JSON.Net你可以添加一个方法:

public bool ShouldSerializeMyObjectList() 
{ 
    return false; 
} 

或者您可以使用JsonIgnore你不想序列化的属性之上,但也将受益于被反序列化阻止他们。

编辑:

JSON.Net自动查找与签名public bool ShouldSerializeProperty()的方法和使用该作为它是否应该序列的特定属性的逻辑。下面是该文档:

https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm

下面是一个例子:

static void Main(string[] args) 
{ 
    var thing = new MyClass 
    { 
     Id = "ID", 
     Description = "Description", 
     Location = "Location", 
     MyObjectLists = new List<MyObject> 
     { 
      new MyObject { Name = "Name1" }, 
      new MyObject { Name = "Name2" } 
     } 
    }; 

    var json = JsonConvert.SerializeObject(thing); 
    Console.WriteLine(json); 
    Console.Read(); 
} 

class MyClass 
{ 
    public string Id { get; set; } 
    public string Description { get; set; } 
    public string Location { get; set; } 
    public List<MyObject> MyObjectLists { get; set; } 

    public bool ShouldSerializeMyObjectLists() 
    { 
     return false; 
    } 
} 

class MyObject 
{ 
    public string Name { get; set; } 
} 

的JSON输出看起来是这样的:{"Id":"ID","Description":"Description","Location":"Location"}

+0

但如何在序列化中使用该功能?我应该把它作为一个论据还是什么? –

+1

你实际上不需要做任何事情。 Json.Net自动查找签名为'bool ShouldSerailizePropertyName'的方法,并在序列化时使用这些方法。我将为示例添加代码。 – GBreen12

2

如果使用Newtonsoft Json.NET那么你可以申请[JsonIgnore]属性到MyObjectLists属性。

public class MyClass 
{ 
    public string Id { get; set; } 
    public string Description { get; set; } 
    public string Location { get; set; } 

    [JsonIgnore] 
    public List<MyObject> MyObjectLists { get; set; } 
} 

更新#1

是的,你能避免[JsonIgnore]属性。你可以写一个自定义JsonConverter

在这里看到的例子:Custom JsonConverter

您也可以使用来自@ GBreen12的ShouldSerialize解决方案。

+0

有没有办法避免JsonIgnore属性? –