2016-01-02 32 views
3

我有一个内部的getter/setter方法类,以防止用户访问此功能(我用REST API的工作)。但是,这也意味着JsonConvert无法访问它们。我如何允许JsonConvert访问内部功能?允许Newtonsoft的JsonConvert访问内部的getter/setter方法

+0

重复:https://stackoverflow.com/questions/26873755/json-serializer-object-with-internal-properties –

回答

3

你应该可以用JsonPropertyAttribute来修饰它们。

void Main() 
{ 
    var x = new Test(); 
    Console.WriteLine(JsonConvert.SerializeObject(x)); 
} 

// Define other methods and classes here 
public class Test { 
    public Test() 
    { 
    TestProp = "test"; 
    } 
    [JsonProperty()] 
    internal string TestProp {get;set;} 
} 

输出:{"TestProp":"test"}

使用Linqpad。

+0

有趣的 - 这似乎已经做了诡计 - 我一直在搞'InternalsVisibleTo'!有没有一种方法我不必为每个拥有内部获取/设置者的财产做这件事,因为有很多? – user3791372

+1

你可以用'[JsonObject(MemberSerialization.Fields)]'装饰类。您也可以使用自定义合约解析器,如下所示:http://stackoverflow.com/a/24107081/5402620 –

相关问题