Data parse from JSON Response - java

I can't parse data from Response:
here is my snippet:
Response = '{"sys":"[{\"division\":\"Barisal\",\"district\":\"Pirojpur Zila\",\"upazilla\":\"Mathbaria Upazila\"},{\"division\":\"Barisal\",\"district\":\"Jhalokati Zila\",\"upazilla\":\"Rajapur Upazila\"},{\"division\":\"Barisal\",\"district\":\"Barguna Zila\",\"upazilla\":\"Amtali Upazila\"},{\"division\":\"Barisal\",\"district\":\"Barisal Zila\",\"upazilla\":\"Banari Para Upazila\"},{\"division\":\"Barisal\",\"district\":\"Pirojpur Zila\",\"upazilla\":\"Pirojpur Sadar Upazila\"},{\"division\":\"Barisal\",\"district\":\"Barisal Zila\",\"upazilla\":\"Muladi Upazila\"}]"}';
JSONObject json = new JSONObject(response);
JSONArray userdetails = json.getJSONArray("sys");
for (int i=0; i<userdetails.length(); i++) {
JSONObject user = userdetails.getJSONObject(i);
String division = user.getString("division");
String district = user.getString("district");
String upazilla = user.getString("upazilla");
}
I debug the code. Code stop when tried to check userdetails length.
Any ideas ?

There should be no " in front of [{ nor after }]
This should work:
String response = "{\"sys\":[{\"division\":\"Barisal\",\"district\":\"Pirojpur Zila\",\"upazilla\":\"Mathbaria Upazila\"},{\"division\":\"Barisal\",\"district\":\"Jhalokati Zila\",\"upazilla\":\"Rajapur Upazila\"},{\"division\":\"Barisal\",\"district\":\"Barguna Zila\",\"upazilla\":\"Amtali Upazila\"},{\"division\":\"Barisal\",\"district\":\"Barisal Zila\",\"upazilla\":\"Banari Para Upazila\"},{\"division\":\"Barisal\",\"district\":\"Pirojpur Zila\",\"upazilla\":\"Pirojpur Sadar Upazila\"},{\"division\":\"Barisal\",\"district\":\"Barisal Zila\",\"upazilla\":\"Muladi Upazila\"}]}";
JSONObject json = new JSONObject(response);
JSONArray userdetails = json.getJSONArray("sys");
for (int i=0; i<userdetails.length(); i++)
{
JSONObject user = userdetails.getJSONObject(i);
String division = user.getString("division");
String district = user.getString("district");
String upazilla = user.getString("upazilla");
}

Sample code :
String JSON_DATA =
"{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " ]"
+ "}";
JSONObject json;
JSONArray geodetails = null;
JSONObject user;
try {
json = new JSONObject(JSON_DATA);
geodetails = json.getJSONArray("geodata");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < geodetails.length(); i++) {
try {
user = geodetails.getJSONObject(i);
String name = user.getString("name");
String gender = user.getString("gender");
String latitude = user.getString("latitude");
Log.d("Json response", " " + name+" "+gender+" "+latitude);
} catch (JSONException e) {
e.printStackTrace();
}
}

Try below format. i.e:
String response = "{\"sys\":[{\"division\":\"Barisal\",\"district\":\"Pirojpur Zila\",\"upazilla\":\"Mathbaria Upazila\"},{\"division\":\"Barisal\",\"district\":\"Jhalokati Zila\",\"upazilla\":\"Rajapur Upazila\"},{\"division\":\"Barisal\",\"district\":\"Barguna Zila\",\"upazilla\":\"Amtali Upazila\"},{\"division\":\"Barisal\",\"district\":\"Barisal Zila\",\"upazilla\":\"Banari Para Upazila\"},{\"division\":\"Barisal\",\"district\":\"Pirojpur Zila\",\"upazilla\":\"Pirojpur Sadar Upazila\"},{\"division\":\"Barisal\",\"district\":\"Barisal Zila\",\"upazilla\":\"Muladi Upazila\"}]}";
And test JSON format here without "\"
& Your code of json parsing is right

Your Json response is not correct. There should not be any codes before JsonArray, response should be like this
{"sys":[{"division":"Barisal","district":"Pirojpur Zila","upazilla":"Mathbaria Upazila"},{"division":"Barisal","district":"Jhalokati Zila","upazilla":"Rajapur Upazila"},{"division":"Barisal","district":"Barguna Zila","upazilla":"Amtali Upazila"},{"division":"Barisal","district":"Barisal Zila","upazilla":"Banari Para Upazila"},{"division":"Barisal","district":"Pirojpur Zila","upazilla":"Pirojpur Sadar Upazila"},{"division":"Barisal","district":"Barisal Zila","upazilla":"Muladi Upazila"}]}

Your json object is:
{
"sys": [{
"division": "Barisal",
"district": "Pirojpur Zila",
"upazilla": "Mathbaria Upazila"
}, {
"division": "Barisal",
"district": "Jhalokati Zila",
"upazilla": "Rajapur Upazila"
}, {
"division": "Barisal",
"district": "Barguna Zila",
"upazilla": "Amtali Upazila"
}, {
"division": "Barisal",
"district": "Barisal Zila",
"upazilla": "Banari Para Upazila"
}, {
"division": "Barisal",
"district": "Pirojpur Zila",
"upazilla": "Pirojpur Sadar Upazila"
}, {
"division": "Barisal",
"district": "Barisal Zila",
"upazilla": "Muladi Upazila"
}]
}
For automatic serialization and deserialization use Gson library. This can be done in Gson in a very simple manner. Go to jsonschematopojo.org and covert your json to pojo classes. the resultant pojo class for your json object is:
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class YourJsonClass {
#SerializedName("sys")
#Expose
private List<Sy> sys = null;
public List<Sy> getSys() {
return sys;
}
public void setSys(List<Sy> sys) {
this.sys = sys;
}
public class Sy {
#SerializedName("division")
#Expose
private String division;
#SerializedName("district")
#Expose
private String district;
#SerializedName("upazilla")
#Expose
private String upazilla;
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getUpazilla() {
return upazilla;
}
public void setUpazilla(String upazilla) {
this.upazilla = upazilla;
}
}
Now to access it, that's got simpler now,
String response = "{\"sys\":[{\"division\":\"Barisal\",\"district\":\"Pirojpur Zila\",\"upazilla\":\"Mathbaria Upazila\"},{\"division\":\"Barisal\",\"district\":\"Jhalokati Zila\",\"upazilla\":\"Rajapur Upazila\"},{\"division\":\"Barisal\",\"district\":\"Barguna Zila\",\"upazilla\":\"Amtali Upazila\"},{\"division\":\"Barisal\",\"district\":\"Barisal Zila\",\"upazilla\":\"Banari Para Upazila\"},{\"division\":\"Barisal\",\"district\":\"Pirojpur Zila\",\"upazilla\":\"Pirojpur Sadar Upazila\"},{\"division\":\"Barisal\",\"district\":\"Barisal Zila\",\"upazilla\":\"Muladi Upazila\"}]}";
Gson g1 = new Gson();
YourJsonClass response2 = g1.fromJson(response, YourJsonClass.class);
Now, you need to iterate the response2 object as per your convenience.
for(int i=0; i < response2.getSys().size(); i++) {
System.out.println(response2.getSys().get(i).getDivision());
System.out.println(response2.getSys().get(i).getDistrict());
System.out.println(response2.getSys().get(i).getUpazilla());
}

Related

How do I get a value from such a JSON Response

This is What i get as a response from the PlacesApi after making a request.
But the issue is that i cant get the value of "photo_reference".
The issue is also the Objects being in Arrays and all , the whole response looks confusing.
Below is what i have tried in android studio Java
private void getUserLocationImage(String mLocationName) {
String url = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input="+mLocationName+"&inputtype=textquery&fields=photos&key="+R.string.google_api;
// prepare the Activities Request
JsonObjectRequest getWeatherRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray dataArray = response.getJSONArray("candidates");
JSONObject photosObj = dataArray.getJSONObject(0);
JSONArray photosArray = photosObj.getJSONArray("photos");
JSONObject photoRefObj = photosArray.getJSONObject(0);
String imageRef = photoRefObj.get("photo_reference").toString();
Toast.makeText(HomeLandingPageActivity.this, ""+imageRef, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
});
// add it to the RequestQueue
queue.add(getWeatherRequest);
}
This is the Error
org.json.JSONException: Index 0 out of range [0..0)
This is what the response is in the Web
{
"candidates" : [
{
"photos" : [
{
"height" : 4160,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/111684034547030396888\"\u003eCaroline Wood\u003c/a\u003e"
],
"photo_reference" : "CmRaAAAAQkMptoZgWJHING5qIR5_abXvnxjhHHEOHmDRH3ZpXUrar5PfpN5tQhhPoPwYmTDjpdVmXeT3T9klnrdK4xMvuudPm309UxMcx_ddbiu6E4shWYaPFn4gO4Diq4mOM46EEhCoo3TLpUbrWhInjelgVtYZGhSDJPyoRefWJ8WIcDs8Bk8VXAwHyQ",
"width" : 3120
}
]
}
],
"status" : "OK"
}
Try to use Gson library for deserilization your response. http://tutorials.jenkov.com/java-json/gson.html
It's very simple way to get any values from response
At first need create class with response model
import java.util.List;
public class ResponseBody {
public List<Candidates> candidates;
public static class Candidates {
public List<Photos> photos;
public static class Photos {
public int height;
public int width;
public String photo_reference;
public List<String> html_attributions;
}
}
}
Then just get your response as String and deserilize it:
String json = "{\n" +
" \"candidates\" : [\n" +
" {\n" +
" \"photos\" : [\n" +
" {\n" +
" \"height\" : 4160,\n" +
" \"html_attributions\" : [\n" +
" \"\\u003ca href=\\\"https://maps.google.com/maps/contrib/111684034547030396888\\\"\\u003eCaroline Wood\\u003c/a\\u003e\"\n" +
" ],\n" +
" \"photo_reference\" : \"CmRaAAAAQkMptoZgWJHING5qIR5_abXvnxjhHHEOHmDRH3ZpXUrar5PfpN5tQhhPoPwYmTDjpdVmXeT3T9klnrdK4xMvuudPm309UxMcx_ddbiu6E4shWYaPFn4gO4Diq4mOM46EEhCoo3TLpUbrWhInjelgVtYZGhSDJPyoRefWJ8WIcDs8Bk8VXAwHyQ\",\n" +
" \"width\" : 3120\n" +
" }\n" +
" ]\n" +
" }\n" +
" ],\n" +
" \"status\" : \"OK\"\n" +
"}";
Gson gson = new Gson();
ResponseBody responseBody = gson.fromJson(json, ResponseBody.class);
System.out.println("responseBody = " + responseBody.candidates.get(0).photos.get(0).photo_reference);
I got this:
responseBody = CmRaAAAAQkMptoZgWJHING5qIR5_abXvnxjhHHEOHmDRH3ZpXUrar5PfpN5tQhhPoPwYmTDjpdVmXeT3T9klnrdK4xMvuudPm309UxMcx_ddbiu6E4shWYaPFn4gO4Diq4mOM46EEhCoo3TLpUbrWhInjelgVtYZGhSDJPyoRefWJ8WIcDs8Bk8VXAwHyQ

Getting null pointer while reading the fileds from JSON to POJO

I have my json as given below which is coming as string. I want to map only two fields in SEGMENT object ex:(TYPE and UN_NUM) to a pojo. I used the following code which is returning null values.
test.json
{
"TEST": {
"NAME": "PART_TRAN",
"VERSION": "9.0",
"ID": "----",
"SEGMENT": {
"TYPE": "R",
"CLIENT_ID": "----",
"UN_NUM": "UN"
}
}
}
test.java
process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
String data = exchange.getIn().getBody(String.class);
try{
XmlMapper xmlMapper = new XmlMapper();
JsonNode jsonNode = xmlMapper.readTree(data.toString());
ObjectMapper objectMapper = new ObjectMapper();
String value = objectMapper.writeValueAsString(jsonNode);
logger.info("Converting XML to JSON {}" , value);
SEGMENT seg = objectMapper.readValue(value, SEGMENT.class);
Test test = new Test(seg);
logger.info("Test Object {}" , test);
}catch (JsonParseException e){
e.printStackTrace();
}catch (JsonMappingException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
}).
SEGMENT.java
#Data
#JsonIgnoreProperties
public class SEGMENT {
#JsonIgnore
private String TYPE;
#JsonIgnore
private String CLIENT_ID;
#JsonIgnore
private String UN_NUM;
}
Test.java
#Data
public class Test {
private String NAME;
private String VERSION;
private String ID;
private SEGMENT segment;
}
Logs:
: Test Object Test(SEGMENT=SEGMENT(TYPE=null, CLIENT_ID =null,UN_NUM =null))
I just added the SEGMENT class which I'm using to map the json.
There is underscore-java library with methods U.fromJsonMap(json) and U.get(map, path). I am the maintainer of the project.
String jsonData = "{\n"
+ " \"TEST\": {\n"
+ " \"NAME\": \"PART_TRAN\",\n"
+ " \"VERSION\": \"9.0\",\n"
+ " \"ID\": \"----\",\n"
+ " \"SEGMENT\": {\n"
+ " \"TYPE\": \"R\",\n"
+ " \"CLIENT_ID\": \"----\",\n"
+ " \"UN_NUM\": \"UN\"\n"
+ " }"
+ " }"
+ "}";
Map<String, Object> jsonObject = U.fromJsonMap(jsonData);
String type = U.<String>get(jsonObject, "TEST.SEGMENT.TYPE");
String unNum = U.<String>get(jsonObject, "TEST.SEGMENT.UN_NUM");
System.out.println(type);
System.out.println(unNum);
Output:
R
UN

I can't parse a Json file to a java object using Gson

I have a Json file like this:
{
"airports": [
{
"fs": "VGO",
"iata": "VGO",
"icao": "LEVX",
"name": "Vigo Airport",
"city": "Vigo",
"cityCode": "VGO",
"stateCode": "SP",
"countryCode": "ES",
"countryName": "Spain and Canary Islands",
"regionName": "Europe",
"timeZoneRegionName": "Europe/Madrid",
"localTime": "2018-01-29T08:59:15.661",
"utcOffsetHours": 1,
"latitude": 42.224551,
"longitude": -8.634025,
"elevationFeet": 860,
"classification": 4,
"active": true,
"weatherUrl": "https://api.flightstats.com/flex/weather/rest/v1/json/all/VGO?codeType=fs",
"delayIndexUrl": "https://api.flightstats.com/flex/delayindex/rest/v1/json/airports/VGO?codeType=fs"
}
]
}
and I want to use to create an airport object.
public class Airport {
String iata;
String name;
String city;
String countryName;
String regionName;
String timeZoneRegionName;
double utcOffsetHours;
double latitude;
double longitude;
int elevationFeet;
#Override
public String toString() {
return "Airports{" +
"iata='" + iata + '\'' +
", name='" + name + '\'' +
", city='" + city + '\'' +
", countryName='" + countryName + '\'' +
", regionName='" + regionName + '\'' +
", timeZoneRegionName='" + timeZoneRegionName + '\'' +
", utcOffsetHours=" + utcOffsetHours +
", latitude=" + latitude +
", longitude=" + longitude +
", elevationFeet=" + elevationFeet +
'}';
}
}
and I read it in the following way:
public void imprimirJson(String fileName) {
String filePath = getCacheDir() + "/" + fileName + ".json";
Gson gson = new Gson();
Airport airport = null;
try {
airport = gson.fromJson(new FileReader(filePath), Airport.class);
} catch (FileNotFoundException e) {
}
Log.i("MSG", airport.toString());
}
But if I execute this code, the Log prints an empty array
public void printJson(String fileName) {
String filePath = getCacheDir() + "/" + fileName + ".json";
Gson gson = new Gson();
Airport airport = null;
try {
airport = gson.fromJson(new FileReader(filePath), Airport.class);
} catch (FileNotFoundException e) {
}
Log.i("MSG", airport.toString());
}
I think that the problem is that the first attribute, has an array of the info that I want. But I don't know how to access the info. Can you show me the way?
create a class MyAirports.java.
public class MyAirports{
List<Airport> airports;
public List<Airport> getAirportList()
{
return this.airports;
}
}
and do,
public void printJson(String fileName) {
String filePath = getCacheDir() + "/" + fileName + ".json";
Gson gson = new Gson();
MyAirports airports = null;
try {
//airport = gson.fromJson(new FileReader(filePath), Airport.class);
airports = gson.fromJson(new FileReader(filePath), MyAirports.class);
} catch (FileNotFoundException e) {
}
Log.i("MSG", airports.getAirportList().get(0).toString());
}
The value of "airports" in your json file is a JsonArray. Hence, you can implement like this:
public void imprimirJson(String fileName) {
String filePath = getCacheDir() + "/" + fileName + ".json";
Gson gson = new Gson();
Airport[] airport = null;
try {
airport = gson.fromJson(new FileReader(filePath), Airport[].class);
} catch (FileNotFoundException e) {
}
Log.i("MSG", airport.toString());
}
Later, airport[0] is what you want to print out.

java fetching json string to class object type not working

In my java-Spring mvc project I have (valid) json string,like:
[{
"name": "sonia",
"emails": [{
"email": "abc#gmail.com",
"type": "Work"
}, {
"email": "xyz#gmail.com",
"type": "office"
}]
}]
I have Email class:
public class Email
{
private String email;
private String type;
//setters & getters
}
User Class
public class User {
private int id;
private String name;
private Set<Email> emails;
//setters and getters
}
I want to jetch json string to my class object type from Above String it will like
sonia
abc#gmail.com
Work
sonia
xyz#gmail.com
Work
So,I have tried the code below:
try {
JSONArray jsonarray = new JSONArray(JsonString);
Gson gson = new Gson();
User[] users = gson.fromJson(jsonarray.toString(), User[].class);
for (int i = 0; i < users.length; i++) {
//fetches name
logger.info(users[i].getName());
//here I want to fetch user with email/emails
logger.info(users[i].getEmails());
//but not getting results
}
} catch (Exception e) {
logger.error("Contact save > Error: " + e.getMessage());
}
For one user I want to receive their emails..but here I am not getting result..what I have to add to achieve my requirement.
I am getting errors:
INFO | 0
INFO | 0
INFO | 0
INFO | 0
...
...
Well I think that you are trying to map json to wrong objects. Take your json and post it here then you should update your objects. I think that you should have after it something like below:
Email class:
public class Email {
private String email;
private String type;
}
User class:
public class User{
private String name;
private List<Email> emails = new ArrayList<Email>();
}
Use ObjectMapper here is reference to documentation. And then have a look at the example by MKyong how to use
This is working solution, you can tune your code accordingly:
public static void main(String args[]) {
String jsonString = "[{\n" +
" \"name\": \"sonia\",\n" +
" \"emails\": [{\n" +
" \"email\": \"abc#gmail.com\",\n" +
" \"type\": \"Work\"\n" +
" }, {\n" +
" \"email\": \"xyz#gmail.com\",\n" +
" \"type\": \"office\"\n" +
" }] \n" +
"}]";
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", "sonia");
JsonArray jsonArray = new JsonArray();
JsonObject jsonObject1 = new JsonObject();
jsonObject1.addProperty("email", "abc#gmail.com");
jsonObject1.addProperty("type", "Work");
JsonObject jsonObject2 = new JsonObject();
jsonObject2.addProperty("email", "xyz#gmail.com");
jsonObject2.addProperty("type", "office");
jsonArray.add(jsonObject1);
jsonArray.add(jsonObject2);
jsonObject.add("emails", jsonArray);
System.out.println(jsonObject.toString());
JsonArray jsonArray1 = new JsonArray();
jsonArray1.add(jsonObject);
Gson gson = new Gson();
User[] users = gson.fromJson(jsonArray1, User[].class);
for (int i = 0; i < users.length; i++) {
System.out.println(users[i].getName());
System.out.print(users[i].getEmails().toString());
}
}
Try this
I think you mean to get the Set's elements
for (int i = 0; i < users.length; i++) {
Set<Email> tempEmail = users[i].getEmails();
Object [] tempEmailObj = tempEmail .toArray();
Email[] email = Arrays.copyOf(tempEmailObj , tempEmailObj .length, Email[].class);
String nemail = email[0].getEmail();
//fetch name
logger.info(users[i].getName());
//fetch user with email
logger.info(nemail);
}
And put also
public Set<Email> getEmails() {
return emails;
}
in the User class

Parse List of JSON objects using GSON

I have a JSON object like this:
{
"user1": {
"timeSpent": "20.533333333333335h",
"worklog": [
{
"date": "06/26/2013",
"issues": [
{
"issueCode": "COC-2",
"comment": "\ncccccc",
"timeSpent": "20.533333333333335h"
}
],
"dayTotal": "20.533333333333335h"
}
]
},
"admin": {
"timeSpent": "601.1h",
"worklog": [
{
"date": "06/25/2013",
"issues": [
{
"issueCode": "COC-1",
"comment": "",
"timeSpent": "113.1h"
}
],
"dayTotal": "113.1h"
},
{
"date": "06/26/2013",
"issues": [
{
"issueCode": "COC-1",
"comment": "",
"timeSpent": "8h"
},
{
"issueCode": "COC-2",
"comment": "",
"timeSpent": "480h"
}
],
"dayTotal": "488h"
}
]
}
}
and trying to parse it with Gson:
Gson gson = new Gson();
Book responseBean = gson.fromJson(jsonString, Book.class);
But the 'responceBean' is always 'null'
Here are all the other classes:
public class Book {
private List<User> user = new LinkedList<User>();
public List<User> getUser() {
return user;
}
public void setUser(List<User> user) {
this.user = user;
}
}
public class User {
private String timeSpent;
private List<WorkLog> worklogs = new LinkedList<WorkLog>();;
public List<WorkLog> getWorklogs() {
return worklogs;
}
public void setWorklogs(List<WorkLog> worklogs) {
this.worklogs = worklogs;
}
public String getTimeSpent() {
return timeSpent;
}
public void setTimeSpent(String timeSpent) {
this.timeSpent = timeSpent;
}
}
public class WorkLog{
private String date;
private String dayTotal;
private List<Issues> issues;
public String getDate(){
return this.date;
}
public void setDate(String date){
this.date = date;
}
public String getDayTotal(){
return this.dayTotal;
}
public void setDayTotal(String dayTotal){
this.dayTotal = dayTotal;
}
public List<Issues> getIssues(){
return this.issues;
}
public void setIssues(List<Issues> issues){
this.issues = issues;
}
}
public class Issues{
private String comment;
private String issueCode;
private String timeSpent;
public String getComment(){
return this.comment;
}
public void setComment(String comment){
this.comment = comment;
}
public String getIssueCode(){
return this.issueCode;
}
public void setIssueCode(String issueCode){
this.issueCode = issueCode;
}
public String getTimeSpent(){
return this.timeSpent;
}
public void setTimeSpent(String timeSpent){
this.timeSpent = timeSpent;
}
}
This is my latest attempt. Somehow I cannot figure out the right way. Will be very appreciative for any help.
Your JSON model does not match your object model.
You need an intermediate layer to fill the gap: a TypeAdapter.
Moreover there is no naming information for the user.
And finally there is a name mismatch: "worklog" in JSON, "worklogs" in Java.
Here is a fixed version:
Java model:
class User {
private String timeSpent;
#SerializedName("worklog")
private List<WorkLog> worklogs = new LinkedList<WorkLog>();
private String name;
public List<WorkLog> getWorklogs() {
return worklogs;
}
public void setWorklog(List<WorkLog> worklogs) {
this.worklogs = worklogs;
}
public String getTimeSpent() {
return timeSpent;
}
public void setTimeSpent(String timeSpent) {
this.timeSpent = timeSpent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The plumbing to fill the gap:
class BookTypeAdapter implements JsonSerializer<Book>, JsonDeserializer<Book>
{
Gson gson = new Gson();
public JsonElement serialize(Book book, Type typeOfT, JsonSerializationContext context)
{
JsonObject json = new JsonObject();
for (User user : book.getUser())
{
json.addProperty(user.getName(), gson.toJson(user));
}
return json;
}
public Book deserialize(JsonElement element, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
JsonObject json = element.getAsJsonObject();
Book book = new Book();
for (Entry<String, JsonElement> entry : json.entrySet())
{
String name = entry.getKey();
User user = gson.fromJson(entry.getValue(), User.class);
user.setName(name);
book.getUser().add(user);
}
return book;
}
}
And a roundtrip:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Book.class, new BookTypeAdapter());
Gson gson = builder.create();
Book book = gson.fromJson("{" +
" \"user1\": {" +
" \"timeSpent\": \"20.533333333333335h\"," +
" \"worklog\": [" +
" {" +
" \"date\": \"06/26/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-2\"," +
" \"comment\": \"\ncccccc\"," +
" \"timeSpent\": \"20.533333333333335h\"" +
" }" +
" ]," +
" \"dayTotal\": \"20.533333333333335h\"" +
" }" +
" ]" +
" }," +
" \"admin\": {" +
" \"timeSpent\": \"601.1h\"," +
" \"worklog\": [" +
" {" +
" \"date\": \"06/25/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-1\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"113.1h\"" +
" }" +
" ]," +
" \"dayTotal\": \"113.1h\"" +
" }," +
" {" +
" \"date\": \"06/26/2013\"," +
" \"issues\": [" +
" {" +
" \"issueCode\": \"COC-1\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"8h\"" +
" }," +
" {" +
" \"issueCode\": \"COC-2\"," +
" \"comment\": \"\"," +
" \"timeSpent\": \"480h\"" +
" }" +
" ]," +
" \"dayTotal\": \"488h\"" +
" }" +
" ]" +
" }" +
"}", Book.class);
String json = gson.toJson(book);
Have a look at my tutorial to get an idea of what is possible with Gson: Java/JSON mapping with Gson
Enjoy! :)
I had some problem before a month. As far as I remember it was because, same as you, I forgot to make "new" to objects. I mean that it should look:
public class User {
private String timeSpent;
private List<WorkLog> worklogs = new List < WorkLog >();
}
Try this and I hope that it will help.
P.S.
Also as Erik Pragt said you have array of Users, not just single one. So you will have to make 1 more class that contains a List < Users >.

Categories

Resources