简体   繁体   English

C#自定义对象的序列化列表

[英]Serialise list of C# custom objects

I am receiving a JSON string from API that is structured in not a good way to be handled in the App. 我从API接收到JSON字符串,该字符串结构不好,无法在App中处理。

I chose to create a custom serialiser for this JSON data (rather then having two different classes for data received and used in app). 我选择为此JSON数据创建一个自定义序列化程序(而不是为应用程序中接收和使用的数据提供两个不同的类)。

Following a lot of tutorials I managed to put together a custom serialiser for a single object. 经过大量教程,我设法为单个对象组合了一个自定义序列化程序。 However, I need to work with lists of these objects (there will be more different data that will come in these weird lists, that needs custom handling). 但是,我需要使用这些对象的列表(这些奇怪的列表中会出现更多不同的数据,需要自定义处理)。

Is there a built in way I can set my custom serialiser to work with each object in the list? 有没有一种内置的方式可以设置自定义序列化程序以使用列表中的每个对象? Or do I need to split the JSON object manually, and feed chunks of it to custom serialiser? 还是我需要手动拆分JSON对象,并将其块提供给自定义序列化程序?

Any other suggestions how to handle this situation is appreciated. 任何其他建议如何处理这种情况表示赞赏。

User class: 用户类别:

[JsonConverter(typeof(UserSerializer))]
    public class User
    {
        public int id;
        public string displayName;
        public string email;
        public int total_points;
        public float total_values;
    }

The deserialiser: 解串器:

public override object ReadJson(JsonReader reader, Type objectType, 
            object existingValue, JsonSerializer serializer)
        {
            JObject jObjectRoot = JObject.Load(reader);
            var root = jObjectRoot.Properties().ToList();
            JObject jObjectData = JObject.Load(root[2].Value.CreateReader());
            var data = jObjectData.Properties().ToList();
            return new User { 
                id = (int)root[1].Value,
                displayName = (string)data[0].Value,
                email = (string)data[1].Value,
                total_points = (int)data[2].Value,
                total_values = (float)data[3].Value
            };
        }

UPDATE: 更新:

Also the code that parses the json string to single user object: 也是将json字符串解析为单个用户对象的代码:

public static void ProcessJSON(string json)
{
    User user = JsonConvert.DeserializeObject<User>(json);
}

And the JSON itself: JSON本身:

[
  {
    "type": "users",
    "id": 1,
    "attr": {
      "display_name": "user2",
      "email": "user2@email.com",
      "total_points": 4,
      "total_values": 32.34
    },
    "relationships": {
      "points_received": {
        "links": {
          "self": "tipjar/users/1/relationships/points",
          "related": "tipjar/users/1/points"
        }
      },
      "points_given": {
        "links": {
          "self": "tipjar/users/1/relationships/awarded",
          "related": "tipjar/users/1/awarded"
        }
      }
    }
  }
]

Thanks 谢谢

You can get the list of user objects without a custom converter like this: 您可以在没有自定义转换器的情况下获得用户对象列表,如下所示:

var userList = JArray.Parse(json)
    .Select(t => new User()
    {
        id = int.Parse(t["id"].ToString()),
        displayName = t["attr"]["display_name"].ToString(),
        email = t["attr"]["email"].ToString(),
        total_points = int.Parse(t["attr"]["total_points"].ToString()),
        total_values = float.Parse(t["attr"]["total_values"].ToString()),
    }).ToList();
public static void ProcessJSON(string json)
{
    User u = new User();
    var test = JsonConvert.DeserializeObject(json);
    if (test.GetType() == typeof(User))
        u = (User)test;

}

Not 100% on how the serialize works, but this seemed to have worked on the test app I made. 不是100%关于序列化的工作方式,但这似乎在我制作的测试应用程序中起作用。

It might be a bit silly. 可能有点傻。 But you could test on the different types of objects returned... 但是您可以测试返回的不同类型的对象...

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

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