How do I get a value from such a JSON Response - java

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

Related

ApolloQueryCall Test in java

I am trying to test onResponse method. If I understand korrectly, when I call apolloQueryCall.enqueue , it should return response as response. When I run this code, it does not enter neither onResponse or onFailere. What am I missing? I could not find examples that work for me on the internet for Java.
String body = "{\n" +
" \"data\": {\n" +
" \"message\": \"kedi\"\n" +
" }\n" +
"}";
MockWebServer webServer = new MockWebServer();
MockResponse response = new MockResponse().setResponseCode(200).setBody(body);
webServer.enqueue(response);
var apolloClient = ApolloClient.builder()
.serverUrl(webServer.url("http://localhost/mock"))
.okHttpClient(okHttpClient)
.build();
var apolloQueryCall = apolloClient.query(query);
apolloQueryCall.enqueue(new ApolloCall.Callback<MyClass.Data>() {
#Override
public void onResponse(#NotNull Response<MyClass.Data> response) {
System.out.println("response:" + response);
}
#Override
public void onFailure(#NotNull ApolloException e) {
System.out.println(e.getMessage());
}
});
webServer.close();

Data parse from JSON Response

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());
}

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.

Edit message contents in OneSignal notification Android

I am trying to change the current 'Test Message' String in a OneSignal push notification. I simply want to use a variable defined in my code, but cannot figure out how to do it.
try {
OneSignal.postNotification(new JSONObject("{'contents': ['en': 'Test Message'], 'include_player_ids': ['" + selectedUser.getOneSignalId() + "']}"),
new OneSignal.PostNotificationResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Log.i("OneSignalExample", "postNotification Success: " + response.toString());
}
#Override
public void onFailure(JSONObject response) {
Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
}
});
} catch (JSONException f) {
e.printStackTrace();
}
I was able to achieve something similar in sending the notification to a selected user. Now I just want to change the text of the actual message.
Use this
String yourVaribale = " what ever you want to send"
OneSignal.postNotification(new JSONObject("{'contents': ['en': " + yourVariable + "], 'include_player_ids': ['" + selectedUser.getOneSignalId() + "']}"),
new OneSignal.PostNotificationResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Log.i("OneSignalExample", "postNotification Success: " + response.toString());
}
#Override
public void onFailure(JSONObject response) {
Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
}
});
} catch (JSONException f) {
e.printStackTrace();
}
or you can try this way
String strJsonBody = "{"
+ " \"app_id\": \"ef42157d-64e7-4ce2-9ab7-15db224f441b\","
+ " \"included_segments\": [\"All\"],"
+ " \"data\": {\"foo\": \"bar\"},"
+ " \"contents\": {\"en\": \""+ description +"\"},"
+ " \"headings\": {\"en\": \""+ title +"\"},"
+ " \"big_picture\":\""+ imageurl +"\""
+ "}";
for second method follow this link
The solution below worked for me. The full name of the current user is concatenated to the string message " wants you to follow them." and is then sent to the selectedUser with the specific OneSignalID.
OneSignal.postNotification(new JSONObject("{'contents': {'en': \""+ currentUser.getFullName() +" wants you to follow them." +"\"}, 'include_player_ids': ['" + selectedUser.getOneSignalId() + "']}"),
new OneSignal.PostNotificationResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Log.i("OneSignalExample", "postNotification Success: " + response.toString());
}
#Override
public void onFailure(JSONObject response) {
Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
}
});

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