Created
March 19, 2012 20:43
-
-
Save yonran/2126973 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static org.junit.Assert.assertEquals; | |
import java.io.BufferedReader; | |
import java.io.StringReader; | |
import java.util.Collection; | |
import org.junit.Test; | |
import com.google.gson.Gson; | |
import com.google.gson.GsonBuilder; | |
public class GsonTest { | |
public class Data { | |
private String serviceNmae; | |
private Collection<Result> results; //Result is inner class below | |
private ErrorResult error; //ErrorResult is inner class below | |
private boolean errorFlag = false; //If an Error has occurred this flag will be true. | |
//getters and setters for the above fields | |
class Result{ | |
private String phoneNum; | |
private String customerLastName; | |
private String customerFirstName; | |
//Getters and Setters for the above fields | |
} | |
class ErrorResult{ | |
private String appErrCode; | |
private String appErrorMsg; | |
//Getters and Setters for the above fields | |
} | |
} | |
@Test | |
public void testJson() { | |
String json = "{" + | |
" \"service\": \"Search\"," + | |
" \"results\": [" + | |
" {" + | |
" \"phoneNum\": \"1234567890\"," + | |
" \"customerLastName\": \"smith\"," + | |
" \"customerFirstName\": \"John\"" + | |
" }," + | |
" {" + | |
" \"phoneNum\": \"9876543210\"," + | |
" \"customerLastName\": \"doe\"," + | |
" \"customerFirstName\": \"jane\"" + | |
" }" + | |
" ]" + | |
"}"; | |
BufferedReader bufferedReader = new BufferedReader(new StringReader(json)); | |
Gson gson = new GsonBuilder().serializeNulls().create(); | |
Data data = gson.fromJson(bufferedReader, Data.class); | |
assertEquals("John", data.results.iterator().next().customerFirstName); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment