Gson,JSON和LinkedTreeMap的微妙之处 [英] Gson, JSON and the subtleties of LinkedTreeMap
问题描述
我最近开始玩弄 JSON
字符串,并被告知Google自己的库 Gson
,是处理这些问题的新方法。
我已经了解它的方式是 JSON
字符串本质上是一张地图。
例如:
<$ c其中每个变量指向字符串中的一个值。 $ c> String jsonInput2 ={\created_at \:\Sat Feb 08 15:37:37 +0000 2014\,\id\:432176397474623489\}
到目前为止,一切都很好。诸如创建 JSON
字符串时的信息可以通过以下代码分配给变量:
Gson gson = new Gson();
地图< String,String> map = new HashMap< String,String>();
map =(Map< String,String>)gson.fromJson(jsonInput,map.getClass());
String createdAt = map.get(created_at);
这简直就是美丽的艺术。但这就是美丽结局和我的困惑开始的地方。
以下是上述 JSON
字符串的扩展;
字符串jsonInput2 ={\created_at \:\Sat Feb 08 15:37:37 + 0000 2014 \,\id \:432176397474623489 \,\user \:{\id_str \:\366301747\,\name \ :\somethingClever \,\screen_name\:\somethingCoolAndClever\}};
我的问题是这些方括号内的方括号如何用于 JSON $ c $的
用户
部分c>?
如何将这些内部括号中指定的值赋值给变量?
任何人都可以向我解释,或者以代码告诉我, Gson
如何处理这样的事情,以及如何使用它?
<总之,为什么......
字符串jsonInput ={\created_at \:\ Sat Feb 08 15:37:37 +0000 2014 \,\id \:432176397474623489 \,\user\:{\id_str \:\366301747\ ,\ name\:\ somethingClever\,\ screen_name\:\ somethingCoolAndClever\}};
Gson gson = new Gson();
地图< String,String> map = new HashMap< String,String>();
map =(Map< String,String>)gson.fromJson(jsonInput,map.getClass());
String name = map.get(name);
System.out.println(name);
...打印出来 null
?
忘记Java。您需要先了解 JSON格式。这基本上就是它
对象
{}
{会员}
会员
对
对,成员
对
字符串:值
数组
[]
[元素]
元素
值
值元素
值
字符串
编号
对象
数组
true
false
null
您的第二个JSON String
(它缺少<$ c
$ b
{$ b>
)是以下内容(使用jsonlint.com进行格式化) $ bcreated_at:Sat Feb 08 15:37:37 +0000 2014,
id:432176397474623489,
user:{
id_str: 366301747,
name:somethingClever,
screen_name:somethingCoolAndClever
}
}
JSON是一个对象,外部 {}
,它包含三对, created_at
这是一个JSON字符串, id
,它也是一个JSON字符串,而 user
这是一个JSON对象。
您询问
如何将这些内部括号中指定的值分配给
变量?
大多数高级JSON解析/生成库是为了将JSON转换为Pojos并返回。
所以你可以将你的JSON格式映射到Java类。
class Pojo {
@SerializedName(created_at)
private String createdAt;
私人字符串ID;
私人用户用户;
}
class User {
@SerializedName(id_str)
private String idStr;
私人字符串名称;
@SerializedName(screen_name)
private String screenName;
}
//带适当的getter,setters和toString()方法
请注意 @SerializedName
,以便您可以继续为字段使用Java命名约定。
您现在可以反序列化您的JSON
Gson gson = new Gson();
Pojo pojo = gson.fromJson(jsonInput2,Pojo.class);
System.out.println(pojo);
会打印
Pojo [createdAt = Sat Feb 08 15:37:37 +0000 2014,id = 432176397474623489,user = User [idStr = 366301747,name = somethingClever,screenName = somethingCoolAndClever]]
显示所有字段设置正确。
任何人都可以向我解释,或以代码显示我,Gson如何处理这样的事情,以及我如何使用它? Gson的源代码是免费的,你可以在网上找到它,它很复杂,源代码的解释不适合这里。简单地说,它使用 Class
对象,以确定它将如何映射JSON对,它会查看相应的类的字段,如果这些字段是其他类,那么它会重复出现,直到它构建了需要反序列化的所有内容的映射。
总之,为什么...打印出null?
因为您的根JSON对象没有名称 name
的对。而不是使用 Map
,使用Gson的 JsonObject
类型。
<$ jsonObject jsonObject = new Gson()。fromJson(jsonInput2,JsonObject.class);
String name = jsonObject.get(user)//获取'user'JsonElement
.getAsJsonObject()//将其作为JsonObject
.get(名称)//获取嵌套的'名称'JsonElement
.getAsString(); //将其作为字符串获取
System.out.println(name);
可以打印
somethingClever
上面的方法类可能会抛出一些例外,正确的类型。例如,如果我们完成了
String name = jsonObject.get(user)//获取'user' JsonElement
.getAsJsonArray()//将它作为JsonArray
它会失败,因为 user
不是JSON数组。具体来说,它会抛出
线程main中的异常java.lang.IllegalStateException:这不是JSON数组。
at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106)
at com.spring.Example.main(Example.java:19)
因此, JsonElement
类(它是 JsonObject $的父类c $ c>,
JsonArray
以及其他一些)提供了一些方法来检查它是什么。查看javadoc。
I've recently started playing around with JSON
strings, and was told that Google's own library, Gson
, is the new and hip way of dealing with these.
The way I've understood it, is that a JSON
string is essentially a map. Where each variable points to a value in the string.
For example:
String jsonInput2 = "{\"created_at\":\"Sat Feb 08 15:37:37 +0000 2014\",\"id\":432176397474623489\"}
Thus far, all is well. Information such as when this JSON
string was created, can be assigned to a variable with the following code:
Gson gson = new Gson();
Map<String, String> map = new HashMap<String, String>();
map = (Map<String, String>) gson.fromJson(jsonInput, map.getClass());
String createdAt = map.get("created_at");
It's almost artistic in in simple beauty. But this is where the beauty ends and my confusion begins.
The following is an extension of the above JSON
string;
String jsonInput2 = "{\"created_at\":\"Sat Feb 08 15:37:37 +0000 2014\",\"id\":432176397474623489\",\"user\":{\"id_str\":\"366301747\",\"name\":\"somethingClever\",\"screen_name\":\"somethingCoolAndClever\"}}";
My question is how these "brackets within brackets" work for the user
section of the JSON
?
How could I assign the values specified within these inner-brackets to variables?
Can anyone explain to me, or show me in code, how Gson
handles stuff like this, and how I can use it?
In short, why does...
String jsonInput = "{\"created_at\":\"Sat Feb 08 15:37:37 +0000 2014\",\"id\":432176397474623489\",\"user\":{\"id_str\":\"366301747\",\"name\":\"somethingClever\",\"screen_name\":\"somethingCoolAndClever\"}}";
Gson gson = new Gson();
Map<String, String> map = new HashMap<String, String>();
map = (Map<String, String>) gson.fromJson(jsonInput, map.getClass());
String name = map.get("name");
System.out.println(name);
... print out null
?
Forget about Java. You need to first understand the JSON format. This is basically it
object
{}
{ members }
members
pair
pair , members
pair
string : value
array
[]
[ elements ]
elements
value
value , elements
value
string
number
object
array
true
false
null
Your second JSON String
(which has a missing "
) is the following (use jsonlint.com to format)
{
"created_at": "Sat Feb 08 15:37:37 +0000 2014",
"id": "432176397474623489",
"user": {
"id_str": "366301747",
"name": "somethingClever",
"screen_name": "somethingCoolAndClever"
}
}
The JSON is an object, outer {}
, that contains three pairs, created_at
which is a JSON string, id
which is also a JSON string, and user
which is a JSON object. That JSON object contains three more pairs which are all JSON strings.
You asked
How could I assign the values specified within these inner-brackets to variables?
Most advanced JSON parsing/generating libraries are meant to convert JSON to Pojos and back.
So you could map your JSON format to Java classes.
class Pojo {
@SerializedName("created_at")
private String createdAt;
private String id;
private User user;
}
class User {
@SerializedName("id_str")
private String idStr;
private String name;
@SerializedName("screen_name")
private String screenName;
}
// with appropriate getters, setters, and a toString() method
Note the @SerializedName
so that you can keep using Java naming conventions for your fields.
You can now deserialize your JSON
Gson gson = new Gson();
Pojo pojo = gson.fromJson(jsonInput2, Pojo.class);
System.out.println(pojo);
would print
Pojo [createdAt=Sat Feb 08 15:37:37 +0000 2014, id=432176397474623489", user=User [idStr=366301747, name=somethingClever, screenName=somethingCoolAndClever]]
showing that all the fields were set correctly.
Can anyone explain to me, or show me in code, how Gson handles stuff like this, and how I can use it?
The source code of Gson is freely available. You can find it online. It is complex and a source code explanation wouldn't fit here. Simply put, it uses the Class
object you provide to determine how it will map the JSON pairs. It looks at the corresponding class's fields. If those fields are other classes, then it recurs until it has constructed a map of everything it needs to deserialize.
In short, why does...print out null?
Because your root JSON object, doesn't have a pair with name name
. Instead of using Map
, use Gson's JsonObject
type.
JsonObject jsonObject = new Gson().fromJson(jsonInput2, JsonObject.class);
String name = jsonObject.get("user") // get the 'user' JsonElement
.getAsJsonObject() // get it as a JsonObject
.get("name") // get the nested 'name' JsonElement
.getAsString(); // get it as a String
System.out.println(name);
which prints
somethingClever
The above method class could have thrown a number of exceptions if they weren't the right type. If, for example, we had done
String name = jsonObject.get("user") // get the 'user' JsonElement
.getAsJsonArray() // get it as a JsonArray
it would fail because user
is not a JSON array. Specifically, it would throw
Exception in thread "main" java.lang.IllegalStateException: This is not a JSON Array.
at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106)
at com.spring.Example.main(Example.java:19)
So the JsonElement
class (which is the parent class of JsonObject
, JsonArray
, and a few others) provides methods to check what it is. See the javadoc.
这篇关于Gson,JSON和LinkedTreeMap的微妙之处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!