Skip to content

Instantly share code, notes, and snippets.

@yonran
Created March 19, 2012 20:43
Show Gist options
  • Save yonran/2126973 to your computer and use it in GitHub Desktop.
Save yonran/2126973 to your computer and use it in GitHub Desktop.
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