-1

我需要一个 JSON -> Pojo -> JSON 转换。

我查看了主流库 Jackson 和 GSON,

显然两者都使用:

//write converted json data to a file named "file.json"
FileWriter writer = new FileWriter("c:\\file.json");

or In\Output Streams..

当我编写新代码时,有两件事最让我害怕:

  1. I\O(特别是高清)
  2. 序列化

我尽量避免这两种情况。

有没有其他方法可以做到这一点?

4

1 回答 1

5

Those libraries DO NOT need to use files to operate, so answering your question: NO, file serialization is not mandatory. In fact it's not only not mandatory, but it'd be such a pain in the ass to read/write from/to a file each time you need to serialize/deserialize a JSON reponse!

In your example they use a File to write and read the JSON in order to imitate the usual scenario, which probably includes pass data from/to a web service for example, instead of from/to a File...

In fact, for example in Gson, serialization/deserialization is quite straightforward with a simple Pojo, just like this:

Serialization

Pojo pojo = new Pojo();
Gson gson = new Gson();
String pojoJSON = gson.toJson(pojo);

Deserialization

Gson gson = new Gson();
Pojo pojo = gson.fromJson(pojoJSON, Pojo.class);

I suggest you to take a look at Gson documentation, which is pretty clear and quite short, once you read it you'll understand everything much better...

于 2013-05-12T18:49:14.723 回答