简体   繁体   English

Json.NET在没有父级的情况下序列化对象属性

[英]Json.NET Serialize Object Properties Without Parent

Using Json.NET is it possible to serialize an object's fields instead of the object itself? 使用Json.NET是否可以序列化对象的字段而不是对象本身?

In JMS Serializer (PHP) I can use the @Inline annotation. 在JMS序列化器(PHP)中,我可以使用@Inline批注。

public class ApiResponseData
{
    public User User { get; set; }
}

public class User
{
    public string Username { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

If I serialize ApiResponseData I would like to get just username, firstname and lastname, not the User property. 如果我序列化ApiResponseData,我只想获取用户名,名字和姓氏,而不是User属性。

Actual: { "user": { "username": "username", "firstname": "firstname", "lastname": "lastname" } } 实际: { "user": { "username": "username", "firstname": "firstname", "lastname": "lastname" } }
Desired: { "username": "username", "firstname": "firstname", "lastname": "lastname" } 期望的: { "username": "username", "firstname": "firstname", "lastname": "lastname" }

You can try to serialize ApiResponseData.User instead of serializing ApiResponseData itself. 您可以尝试序列化ApiResponseData.User而不是序列化ApiResponseData本身。 This way it will only serialize the values of ApiResponseData.User . 这样,它将仅序列化ApiResponseData.User的值。 Like: 喜欢:

 Newtonsoft.Json.JsonConvert.SerializeObject(ApiResponseData.User);

In the classes that contain objects of this class, you can add internal properties that return the value of the member you wish to serialize. 在包含此类对象的类中,可以添加内部属性,这些属性返回要序列化的成员的值。 Not the most elegant solution, but it works. 不是最优雅的解决方案,但它可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM