将 JSON 数据转换为 Java 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1688099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting JSON data to Java object
提问by Faiyet
I want to be able to access properties from a JSON string within my Java action method. The string is available by simply saying myJsonString = object.getJson()
. Below is an example of what the string can look like:
我希望能够从我的 Java 操作方法中的 JSON 字符串访问属性。只需说 即可获得该字符串myJsonString = object.getJson()
。以下是字符串外观的示例:
{
'title': 'ComputingandInformationsystems',
'id': 1,
'children': 'true',
'groups': [{
'title': 'LeveloneCIS',
'id': 2,
'children': 'true',
'groups': [{
'title': 'IntroToComputingandInternet',
'id': 3,
'children': 'false',
'groups': []
}]
}]
}
In this string every JSON object contains an array of other JSON objects. The intention is to extract a list of IDs where any given object possessing a group property that contains other JSON objects. I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string?
在这个字符串中,每个 JSON 对象都包含一个其他 JSON 对象的数组。目的是提取 ID 列表,其中任何给定对象拥有包含其他 JSON 对象的组属性。我将 Google 的 Gson 视为一个潜在的 JSON 插件。任何人都可以就如何从这个 JSON 字符串生成 Java 提供某种形式的指导吗?
采纳答案by BalusC
I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string?
我将 Google 的 Gson 视为一个潜在的 JSON 插件。任何人都可以就如何从这个 JSON 字符串生成 Java 提供某种形式的指导吗?
Google Gsonsupports generics and nested beans. The []
in JSON represents an array and should map to a Java collection such as List
or just a plain Java array. The {}
in JSON represents an object and should map to a Java Map
or just some JavaBean class.
Google Gson支持泛型和嵌套 bean。的[]
在JSON表示一个数组,应映射到Java集合诸如List
或者只是一个普通的Java阵列。将{}
在JSON表示一个对象,应该映射到JavaMap
或只是一些JavaBean类。
You have a JSON object with several properties of which the groups
property represents an array of nested objects of the very same type. This can be parsed with Gson the following way:
您有一个具有多个属性的 JSON 对象,其中的groups
属性表示一组相同类型的嵌套对象。这可以通过以下方式使用 Gson 解析:
package com.stackoverflow.q1688099;
import java.util.List;
import com.google.gson.Gson;
public class Test {
public static void main(String... args) throws Exception {
String json =
"{"
+ "'title': 'Computing and Information systems',"
+ "'id' : 1,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Level one CIS',"
+ "'id' : 2,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Intro To Computing and Internet',"
+ "'id' : 3,"
+ "'children': 'false',"
+ "'groups':[]"
+ "}]"
+ "}]"
+ "}";
// Now do the magic.
Data data = new Gson().fromJson(json, Data.class);
// Show it.
System.out.println(data);
}
}
class Data {
private String title;
private Long id;
private Boolean children;
private List<Data> groups;
public String getTitle() { return title; }
public Long getId() { return id; }
public Boolean getChildren() { return children; }
public List<Data> getGroups() { return groups; }
public void setTitle(String title) { this.title = title; }
public void setId(Long id) { this.id = id; }
public void setChildren(Boolean children) { this.children = children; }
public void setGroups(List<Data> groups) { this.groups = groups; }
public String toString() {
return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
}
}
Fairly simple, isn't it? Just have a suitable JavaBean and call Gson#fromJson()
.
相当简单,不是吗?只要有一个合适的 JavaBean 并调用Gson#fromJson()
.
See also:
也可以看看:
- Json.org- Introduction to JSON
- Gson User Guide- Introduction to Gson
回答by Juanma
If you use any kind of special maps with keys or values also of special maps, you will find it's not contemplated by the implementation of google.
如果您使用任何类型的带有特殊映射键或值的特殊映射,您会发现 google 的实现并没有考虑到它。
回答by Jor
Bewaaaaare of Gson! It's very cool, very great, but the second you want to do anything other than simple objects, you could easily need to start building your own serializers (which isn't thathard).
Gson 的 Bewaaaaare!这是一项很棒,很了不起,但是你想要做的不是简单的对象以外的任何第二,你可以很容易地需要开始建立自己的串行器(这是不是说硬)。
Also, if you have an array of Objects, and you deserialize some json into that array of Objects, the true types are LOST! The full objects won't even be copied! Use XStream.. Which, if using the jsondriver and setting the proper settings, will encode ugly types into the actual json, so that you don't loose anything. A small price to pay (ugly json) for true serialization.
此外,如果您有一个对象数组,并且您将一些 json 反序列化为该对象数组,则真正的类型丢失了!甚至不会复制完整的对象!使用 XStream .. 如果使用 jsondriver 并设置正确的设置,会将丑陋的类型编码到实际的 json 中,这样您就不会丢失任何东西。为真正的序列化付出很小的代价(丑陋的 json)。
Note that Hymansonfixes these issues, and is fasterthan GSON.
回答by StaxMan
Oddly, the only decent JSON processor mentioned so far has been GSON.
奇怪的是,到目前为止提到的唯一像样的 JSON 处理器是 GSON。
Here are more good choices:
这里有更多不错的选择:
- Hymanson(Github) -- powerful data binding (JSON to/from POJOs), streaming (ultra fast), tree model (convenient for untyped access)
- Flex-JSON-- highly configurable serialization
- Hymanson( Github) -- 强大的数据绑定(JSON 到/来自 POJO)、流(超快)、树模型(方便无类型访问)
- Flex-JSON——高度可配置的序列化
EDIT (Aug/2013):
编辑(2013 年 8 月):
One more to consider:
还有一个要考虑的:
- Genson-- functionality similar to Hymanson, aimed to be easier to configure by developer
- Genson-- 类似于 Hymanson 的功能,旨在让开发人员更容易配置
回答by cherouvim
If, by any change, you are in an application which already uses http://restfb.com/then you can do:
如果通过任何更改,您在一个已经使用http://restfb.com/的应用程序中,那么您可以执行以下操作:
import com.restfb.json.JsonObject;
...
JsonObject json = new JsonObject(jsonString);
json.get("title");
etc.
等等。
回答by Gene De Lisa
Or with Hymanson:
或与Hyman逊:
String json = "...
ObjectMapper m = new ObjectMapper();
Set<Product> products = m.readValue(json, new TypeReference<Set<Product>>() {});
回答by HEAT
HashMap keyArrayList = new HashMap();
Iterator itr = yourJson.keys();
while (itr.hasNext())
{
String key = (String) itr.next();
keyArrayList.put(key, yourJson.get(key).toString());
}
回答by Kevin
What's wrong with the standard stuff?
标准的东西有什么问题?
JSONObject jsonObject = new JSONObject(someJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
String value = jsonArray.optJSONObject(i).getString("someJsonValue");
回答by RickHigh
Give boon a try:
试试恩惠:
https://github.com/RichardHightower/boon
https://github.com/RichardHightower/boon
It is wicked fast:
它很快就邪恶了:
https://github.com/RichardHightower/json-parsers-benchmark
https://github.com/RichardHightower/json-parsers-benchmark
Don't take my word for it... check out the gatling benchmark.
不要相信我的话......查看加特林基准。
https://github.com/gatling/json-parsers-benchmark
https://github.com/gatling/json-parsers-benchmark
(Up to 4x is some cases, and out of the 100s of test. It also has a index overlay mode that is even faster. It is young but already has some users.)
(在某些情况下高达 4x,并且在 100 次测试中。它还具有更快的索引覆盖模式。它很年轻,但已经有一些用户。)
It can parse JSON to Maps and Lists faster than any other lib can parse to a JSON DOM and that is without Index Overlay mode. With Boon Index Overlay mode, it is even faster.
它可以将 JSON 解析为 Maps 和 Lists 的速度比任何其他 lib 解析为 JSON DOM 的速度都要快,而且没有索引覆盖模式。使用 Boon Index Overlay 模式,速度更快。
It also has a very fast JSON lax mode and a PLIST parser mode. :) (and has a super low memory, direct from bytes mode with UTF-8 encoding on the fly).
它还具有非常快的 JSON 松散模式和 PLIST 解析器模式。:)(并且具有超低内存,直接从带有 UTF-8 编码的字节模式中运行)。
It also has the fastest JSON to JavaBean mode too.
它还具有最快的 JSON 到 JavaBean 模式。
It is new, but if speed and simple API is what you are looking for, I don't think there is a faster or more minimalist API.
它是新的,但如果您正在寻找速度和简单的 API,我认为没有更快或更简约的 API。
回答by Shailendra Singh
Depending on the input JSON format(string/file) create a jSONString. Sample Message class object corresponding to JSON can be obtained as below:
根据输入的 JSON 格式(字符串/文件)创建一个 jSONString。JSON对应的Message类对象示例如下:
Message msgFromJSON = new ObjectMapper().readValue(jSONString, Message.class);
Message msgFromJSON = new ObjectMapper().readValue(jSONString, Message.class);