Java7
Posts tagged json
Parsing a JSON String into an object with GSON easily.
Jul 6th
I came across this question from Stackoverflow.com today and quite answered it. That was quite the first time i was using the GSON library as i have always been in and out of json.org’s implementation.
The person wanted to parse in this JSON string, and manipulate in OO easily:
JSON Raw Text
{"DebugLogId":"1750550","RequestId":"17505503","Result":
{"Code":"","DebugLogId":"1750550","Message":""},
"Suggestions":[
{"Ranking":"1","Score":"60","Title":"This is a test message 1"},
{"Ranking":"2","Score":"60","Title":"This is a test message 2"}
]}
Download Eclipse Project Files (1):
Download (12kb) – play-sof-java-6596072
Source codes (4):
Apps.java:
package sg.java.play_sof_json_6596072;
import com.google.gson.Gson;
public class App {
public static void main(String[] args) {
Gson gson = new Gson();
String jsonString = "{\"DebugLogId\":\"1750550\",\"RequestId\":\"17505503\",\"Result\":{\"Code\":\"\",\"DebugLogId\":\"1750550\",\"Message\":\"\"},\"Suggestions\":[{\"Ranking\":\"1\",\"Score\":\"60\",\"Title\":\"This is a test message 1\"},{\"Ranking\":\"2\",\"Score\":\"60\",\"Title\":\"This is a test message 2\"}]}";
Debug obj = (Debug) gson.fromJson(jsonString, Debug.class);
System.out.println(obj.getSuggestionList().get(1).getTitle());
}
}
Debug.java:
package sg.java.play_sof_json_6596072;
import java.util.List;
import com.google.gson.annotations.SerializedName;
public class Debug {
@SerializedName("DebugLogId")
private String debugLogId;
@SerializedName("RequestId")
private String requestId;
@SerializedName("Result")
private Result result;
@SerializedName("Suggestions")
private List<Suggestion> suggestionList;
/**
* @return the debugLogId
*/
public final String getDebugLogId() {
return this.debugLogId;
}
/**
* @param debugLogId the debugLogId to set
*/
public final void setDebugLogId(String debugLogId) {
this.debugLogId = debugLogId;
}
/**
* @return the requestId
*/
public final String getRequestId() {
return this.requestId;
}
/**
* @param requestId the requestId to set
*/
public final void setRequestId(String requestId) {
this.requestId = requestId;
}
/**
* @return the result
*/
public final Result getResult() {
return this.result;
}
/**
* @param result the result to set
*/
public final void setResult(Result result) {
this.result = result;
}
/**
* @return the suggestionList
*/
public final List<Suggestion> getSuggestionList() {
return this.suggestionList;
}
/**
* @param suggestionList the suggestionList to set
*/
public final void setSuggestionList(List<Suggestion> suggestionList) {
this.suggestionList = suggestionList;
}
}
Result.java:
package sg.java.play_sof_json_6596072;
import com.google.gson.annotations.SerializedName;
public class Result {
@SerializedName("Code")
private String code;
@SerializedName("DebugLogId")
private String debugLogId;
@SerializedName("Message")
private String messahe;
/**
* @return the code
*/
public final String getCode() {
return this.code;
}
/**
* @param code the code to set
*/
public final void setCode(String code) {
this.code = code;
}
/**
* @return the debugLogId
*/
public final String getDebugLogId() {
return this.debugLogId;
}
/**
* @param debugLogId the debugLogId to set
*/
public final void setDebugLogId(String debugLogId) {
this.debugLogId = debugLogId;
}
/**
* @return the messahe
*/
public final String getMessahe() {
return this.messahe;
}
/**
* @param messahe the messahe to set
*/
public final void setMessahe(String messahe) {
this.messahe = messahe;
}
}
Suggestion.java:
package sg.java.play_sof_json_6596072;
import com.google.gson.annotations.SerializedName;
public class Suggestion {
@SerializedName("Ranking")
private String ranking;
@SerializedName("Score")
private String score;
@SerializedName("Title")
private String title;
/**
* @return the ranking
*/
public final String getRanking() {
return this.ranking;
}
/**
* @param ranking the ranking to set
*/
public final void setRanking(String ranking) {
this.ranking = ranking;
}
/**
* @return the score
*/
public final String getScore() {
return this.score;
}
/**
* @param score the score to set
*/
public final void setScore(String score) {
this.score = score;
}
/**
* @return the title
*/
public final String getTitle() {
return this.title;
}
/**
* @param title the title to set
*/
public final void setTitle(String title) {
this.title = title;
}
}
And thanks to Maven, project dependency and setup was a two minutes job.
Here is the dependency pom.xml snippet:
<!-- Gson: Java to Json conversion -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.1</version>
<scope>compile</scope>
</dependency>
Reference
Starting JSON, a practical approach. Part 1
Nov 20th
Introduction
Most of us are familiar with basic XML data format because it is greatly understood and is itself a key enabler of many technologies and concepts, the most prominent – web services.
However, XML itself when used in transportation of data over HTTP protocol carries a substantial amount of by product i.e. the descriptive markup tags itself. JavaScript Object Notation (JSON) in comparison is lightweight, lean, and can be as easily understood by the human eye as its XML counterpart when viewed with a JSON formatting phaser.
Just recently, my colleague was tasked with the challenge of minimizing the HTTP content and exchange of a particular use case which has heavy XML. His proposal – gun zipping the XML. I would be curious if he would be able to do a comparison for his solution, and a solution using JSON.
1. Simple object with one domain data
Lets see we have a Zoo called ‘Cityhall State Zoo’ that we need to represent in markup.
XML
<Zoo>Cityhall State Zoo</Zoo>
JSON
{"Zoo": "Cityhall State Zoo"}
2. Simple object with more than one domain data
Our Zoo has now a need to accommodate a Lion.
XML
<Zoo>
<Name>Cityhall State Zoo</Name>
<Animal>Lion</Animal>
</Zoo>
JSON
{"Zoo": {"name": "Cityhall State Zoo", "animal": "Lion"}}
3. Simple object with an array of domain data
We are having more animals in the Zoo than when we had when we first started off!
XML
<Zoo>
<name>Cityhall State Zoo</name>
<Animals>
<Animal>Lion</Animal>
<Animal>Tiger</Animal>
<Animal>Elephant</Elephant>
</Animals>
</Zoo>
JSON
{"Zoo": {"name": "Cityhall State Zoo", "animals": ["Lion", "Tiger", "Elephant"]}}
4. An array of domain objects
So far above we have been having only domain data in our array, for example, String data or Integer data. You may contain domain objects in your array.
XML
<Zoo>
<name>Cityhall State Zoo</name>
<Animals>
<Animal>
<name>Lion</name>
<weight>3.45kg</weight>
<kingdom>Animalia</kingdom>
</Animal>
<Animal>
<name>Tiger</name>
<weight>5kg</weight>
<kingdom>Animalia</kingdom>
</Animal>
</Animals>
</Zoo>
JSON
{"Zoo":{"name":"Cityhall State Zoo", "Animals":[{"Animal":{"name":"Lion", "weight":"3.45kg", "kingdom":"Animalia"}},{"Animal":{"name":"Tiger", "weight":"5kg", "kingdom":"Animalia"}}]}}
Interesting Reads
Look at this stackoverflow question regarding a malformed JSON string, some parser are more tolerant, while some are stricter. So watch out!
Revision
March 21, 2011 Improved XML readability with tab formatting. Edited introductory text.
July 7, 2011 Added a link to a stackoverflow question on JSON string parsing.