简体   繁体   English

如何使用Twitter4j存储和加载用户

[英]How to store and load User with Twitter4j

In Twitter4j, you get a user object like following, 在Twitter4j中,您将获得如下用户对象,

User user = twitter.showUser(userID);

Now, I want to store this user in a text file. 现在,我想将此用户存储在一个文本文件中。 I'm using the toString() method of the User . 我正在使用UsertoString()方法。

It gives me something like the following: 它给了我类似以下内容:

UserJSONImpl{id=xxxxxx, name='xxxx xxxxx', screenName='xxxxxx', ... }

Questions: 问题:

  1. Is using toString() method of User for storing purposes legitimate? 使用User toString()方法进行存储是否合法?

  2. How to load a user using this UserJSONImpl text? 如何使用此UserJSONImpl文本加载用户? I need something like the following: 我需要以下内容:

User user = new User(UserJSONImpl);

I think relying directly on toString() for this is a bad idea because changes to this method are out of your control. 我认为直接依赖toString()是个坏主意,因为对此方法的更改不在您的控制范围内。 For example, what if the format changes or a new field is added? 例如,如果格式更改或添加了新字段怎么办? How do you know when you come to deserializing the data? 当您要反序列化数据时,您怎么知道?

You could use a library to write the User objects in a standard format, for example use GSON to write JSON - but it's still not nice, you have to deal with UserJSONImpl objects which is an internal representation of User . 您可以使用库以标准格式编写User对象,例如,使用GSON编写JSON-但这仍然不太好,您必须处理UserJSONImpl对象,它是User的内部表示形式。

Either way, you could still be exposed to the risk of changes in the User object. 无论哪种方式,您仍然可能会面临User对象发生更改的风险。 I would consider using the User objects to build an object relevant the problem domain, and then persist these objects. 我会考虑使用User对象来构建与问题域相关的对象,然后持久化这些对象。

The idea is that the component that's responsible for the Twitter4J User -> problem domain object conversion can handle different Twitter4J User objects and provide a consistent view for your application. 这个想法是负责Twitter4J User -> problem domain object转换的组件可以处理不同的Twitter4J User对象,并为您的应用程序提供一致的视图。 Although without more context this may be complete overkill, you should be able to judge this better. 尽管没有更多背景信息,这可能完全是矫kill过正,但您应该能够更好地做出判断。 I hope this helps somewhat! 我希望这会有所帮助!

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

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