Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NonSerialized不生效 #126

Open
hahaCrazy opened this issue Jun 18, 2021 · 2 comments
Open

NonSerialized不生效 #126

hahaCrazy opened this issue Jun 18, 2021 · 2 comments

Comments

@hahaCrazy
Copy link

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

@devlead
Copy link
Member

devlead commented Jun 18, 2021

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
Copy link

MyPure commented Dec 17, 2022

你可以改造源码,添加[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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants