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
?