2

我想从服务器解析 json 并将其放入一个类中。我为此使用json4s。问题是 json 对象包含太多字段,大约有 40-50 个,其中一些具有长名称。

我想知道,存储所有这些字段的明智方法是什么,我必须在一个类中创建 40-50 个字段吗?请记住,正如我之前所说,其中一些名称会很长。

我用的是Scala,但是Java的做法可能和它差不多,所以我也加了一个Java的标签。

4

2 回答 2

1

I don't know json4s but in Jersey with Jackson, for example, you can use a Map to hold the Json data or you can use a POJO with all those names.

Sometimes its better to have the names. It makes the code much easier to understand.

Sometimes its better to use a Map. For example, if the field names change from time to time.

If I recall it correctly, using pure Jackson you do something like this:

String jsonString = ....; // This is the string of JSON stuff
JsonFactory factory = new JsonFactory(); 
ObjectMapper mapper = new ObjectMapper(factory);  // A Jackson class
Map<String,Object> data = mapper.readValue(jsonString, HashMap.class); 

You can use a TypeReference to make it a little cleaner as regards the generics. Jackson docs tell more about it. There is also more here: StackOverflow: JSON to Map

于 2013-06-04T17:08:16.697 回答
1

将json解析为对象一般有两种方式 1) 将json解析为对象表示。当您提到您的对象有太多字段时,另一个可能适合您的是 amap/hashtable,或者您可以将其保留为 JObject,获取您需要的字段

于 2013-06-04T17:10:51.447 回答