LitJSON / litjson

JSON library for the .Net framework
https://litjson.net/
Other
1.36k stars 403 forks source link

NonSerialized不生效 #126

Open hahaCrazy opened 3 years ago

hahaCrazy commented 3 years ago

我想在序列化对象时,让某些成员变量不被序列化,于是使用了NonSerialized属性,但是该成员最终还是被序列化了,请问有什么好的解决方法吗

devlead commented 3 years ago

There's no built-in support for attributes in LitJson.

Behavior is controlled either through a delegate or property modifier access.

Example a custom exporter for a type

Class

public class HelloWorld 
{
    public string ShouldNotBeInJson { get; set; }
    public string Message { get; set; }
}

Register Exporter delegate

LitJson.JsonMapper.RegisterExporter<HelloWorld>((obj, writer) => {
    writer.WriteObjectStart();
    writer.WritePropertyName("Message");
    writer.Write(obj.Message);
    writer.WriteObjectEnd();
});

Usage

var toObject = new HelloWorld {
    Message = "Hello world!",
    ShouldNotBeInJson = "Hello"
};

var toJson = LitJson.JsonMapper.ToJson(toObject);

Console.WriteLine("To JSON: {0}", toJson);

Output

To JSON: {"Message":"Hello world!"}

Example using access modifier

Class

public class HelloWorld 
{
    internal string ShouldNotBeInJson { get; set; }
    public string Message { get; set; }
}

Usage

var toObject = new HelloWorld {
    Message = "Hello world!",
    ShouldNotBeInJson = "Hello"
};

var toJson = LitJson.JsonMapper.ToJson(toObject);

Console.WriteLine("To JSON: {0}", toJson);

Output

To JSON: {"Message":"Hello world!"}
MyPure commented 1 year ago

你可以改造源码,添加[JsonIgnore]标签,来让特定的字段不被序列化: 在JsonMapper.cs的WriteValue方法中,有这么一段,加上这几句即可

// Okay, so it looks like the input should be exported as an
// object
AddTypeProperties (obj_type);
IList<PropertyMetadata> props = type_properties[obj_type];
writer.WriteObjectStart ();

foreach (PropertyMetadata p_data in props)
{
    var skipAttributesList = p_data.Info.GetCustomAttributes(typeof(JsonIgnore), true);
    var skipAttributes = skipAttributesList as ICollection<Attribute>;
    if (skipAttributes.Count > 0)
    {
        continue;
    }
...
}

来源:http://wjhsh.net/msxh-p-12541159.html