Parse List of JSON objects using GSON - java

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 >.

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

POST data with retrofit2, Bearer token Unauthorized android

I want to post new data to server with this JSON:
{
"tgl_Lahir": "1990-12-18 00:00:00",
"nama": "Joe",
"keterangan": "Employee",
"tempatLahir": "Los Angeles",
"noPegawai": "111111",
"golDarah": "0",
"statusNikah": "0",
"hubungans": {
"id": "10"
},
"agama": {
"id_Agama": "1"
},
"jeniskelamin": {
"jenisKelamin": "1"
}
}
Here's my ApiClientPOST.java:
public class ApiClientPOST {
private static Retrofit retrofit = null;
public static Retrofit getClient(String url){
if(retrofit == null){
retrofit = new Retrofit.Builder().baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Here's my APIUtils.java:
public class APIUtils {
private APIUtils(){
};
public static final String API_URL = "IPAddress/employee/family/add";
public static MainInterface getUserService(){
return ApiClientPOST.getClient(API_URL).create(MainInterface.class);
}
}
Here's my familylistresponsePOST.java:
public class familylistresponsePOST {
#SerializedName("noPegawai")
private String noPegawai;
#SerializedName("date_otor")
private Object dateOtor;
#SerializedName("jeniskelamin")
private Jeniskelamin jeniskelamin;
#SerializedName("keterangan")
private String keterangan;
#SerializedName("hubungans")
private Hubungans hubungans;
#SerializedName("tgl_Lahir")
private String tglLahir;
#SerializedName("nama")
private String nama;
#SerializedName("agama")
private Agama agama;
#SerializedName("statusNikah")
private String statusNikah;
#SerializedName("tempatLahir")
private String tempatLahir;
#SerializedName("id")
private int id;
#SerializedName("golDarah")
private String golDarah;
public void setNoPegawai(String noPegawai){
this.noPegawai = noPegawai;
}
public String getNoPegawai(){
return noPegawai;
}
public void setDateOtor(Object dateOtor){
this.dateOtor = dateOtor;
}
public Object getDateOtor(){
return dateOtor;
}
public void setJeniskelamin(Jeniskelamin jeniskelamin){
this.jeniskelamin = jeniskelamin;
}
public Jeniskelamin getJeniskelamin(){
return jeniskelamin;
}
public void setKeterangan(String keterangan){
this.keterangan = keterangan;
}
public String getKeterangan(){
return keterangan;
}
public void setHubungans(Hubungans hubungans){
this.hubungans = hubungans;
}
public Hubungans getHubungans(){
return hubungans;
}
public void setTglLahir(String tglLahir){
this.tglLahir = tglLahir;
}
public String getTglLahir(){
return tglLahir;
}
public void setNama(String nama){
this.nama = nama;
}
public String getNama(){
return nama;
}
public void setAgama(Agama agama){
this.agama = agama;
}
public Agama getAgama(){
return agama;
}
public void setStatusNikah(String statusNikah){
this.statusNikah = statusNikah;
}
public String getStatusNikah(){
return statusNikah;
}
public void setTempatLahir(String tempatLahir){
this.tempatLahir = tempatLahir;
}
public String getTempatLahir(){
return tempatLahir;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setGolDarah(String golDarah){
this.golDarah = golDarah;
}
public String getGolDarah(){
return golDarah;
}
#Override
public String toString(){
return
"ListUserResponse2{" +
"noPegawai = '" + noPegawai + '\'' +
",date_otor = '" + dateOtor + '\'' +
",jeniskelamin = '" + jeniskelamin + '\'' +
",keterangan = '" + keterangan + '\'' +
",hubungans = '" + hubungans + '\'' +
",tgl_Lahir = '" + tglLahir + '\'' +
",nama = '" + nama + '\'' +
",agama = '" + agama + '\'' +
",statusNikah = '" + statusNikah + '\'' +
",tempatLahir = '" + tempatLahir + '\'' +
",id = '" + id + '\'' +
",golDarah = '" + golDarah + '\'' +
"}";
}
}
I've tried to create this method and use it on my Button.setOnClickListener:
public void addFamily(String noPegawai,String agama, String hubungan, String jenisKelamins, String tgl_Lahir, String nama, String keterangan, String tempatLahir, String golDarah, String statusNikah){
SharedPreferences preferences = getSharedPreferences("MyPref",0);
String tokens = preferences.getString("userToken",null);
Call<familylistresponse> call = apiService.addFams(noPegawai,agama, hubungan, jenisKelamins, tgl_Lahir , nama, keterangan, tempatLahir, golDarah, statusNikah, "Bearer" + tokens);
call.enqueue(new Callback<familylistresponse>() {
#Override
public void onResponse(Call<familylistresponse> call, Response<familylistresponse> response) {
// if (response.isSuccessful()){
familylistresponse resultsData = new familylistresponse();
resultsData= response.body();
Toast.makeText(TambahDataKeluarga.this,"Data Berhasil Ditambahkan!" + resultsData, Toast.LENGTH_SHORT).show();
// }
}
#Override
public void onFailure(Call<familylistresponse> call, Throwable t) {
Log.e("ERROR: ", t.getMessage());
}
});
}
This one is my tambah Button:
tambah.setOnClickListener(v -> {
SharedPreferences preferences = getSharedPreferences("MyPref",0);
String noPegawai = preferences.getString("noPegawai",null);
String snopeg = etNoPegawai.getText().toString().trim();
String snama = etNama.getText().toString().trim();
String stmpLahir = etTmptLahir.getText().toString().trim();
String stglLahir = etTglLahir.getText().toString().trim();
String sketerangan = etKeterangan.getText().toString().trim();
String sgoldar = etGoldar.getText().toString().trim();
String sstatusnikah = etStatusNikah.getText().toString().trim();
valueJenisKelamin = jeniskelamin.getSelectedItem().toString();
valueHubungan = spHubungans.getSelectedItem().toString();
valueAgama = spAgama.getSelectedItem().toString();
familylistresponse f = new familylistresponse();
f.setNoPegawai(snopeg);
agamas.setAgama(spAgama.getSelectedItem().toString().trim());
jks.setJenisKelamin(jeniskelamin.getSelectedItem().toString().trim());
hubungans.setHubungan(spHubungans.getSelectedItem().toString().trim());
addFamily(snopeg, valueAgama, valueHubungan, valueJenisKelamin, stglLahir, snama, sketerangan, stmpLahir, sgoldar, sstatusnikah);
Log.d(f.getNama(),f.getGolDarah());
Toast.makeText(TambahDataKeluarga.this,"No pegawai "+ noPegawai + " Nama Pegawai "+ snama+ " Tgl Lahir "+ stglLahir
+ " Agama " + valueAgama
+ " Hubungan " + valueHubungan
+ " Jenis Kelamin " + valueJenisKelamin
+ " Tgl Lahir " + stglLahir
+ " Keterangan " + sketerangan
+ " Tempat Lahir " + stmpLahir
+ " Goldar " + sgoldar
+ " Status Nikah " + sstatusnikah,Toast.LENGTH_LONG).show();
});
The toast says that the data is successfully stored but in fact, it isn't. The toast also says that response.body() is null and there is no error in logcat even in the debugger. Please kindly help me. Thanks in advance for any help
I do not see where you are defining Hubungans, Agama and Jeniskelamin classes although you are using it as datatype inside your familylistresponsePOST.java
After creating these three classes, I hope your issue will be solved.

I can't get data of object in json

I have json file with an object
{
"id": 387,
"name": "flatFive",
"coordinates": {
"x": 9.6,
"y": 2.2
},
"creationDate": {
"year": 2020,
"monthValue": 4,
"month": "APRIL",
"dayOfMonth": 1,
"dayOfYear": 92,
"dayOfWeek": "WEDNESDAY",
"hour": 20,
"minute": 40,
"second": 47,
"nano": 662000000,
"chronology": {
"id": "ISO",
"calendarType": "iso8601"
}
},
"area": 332.3,
"numberOfRooms": 3,
"furnish": "bad",
"view": "NORMAL",
"transport": "NONE",
"house": {
"name": "Cottage",
"year": 3,
"numberOfLifts": 6
}
so, how can I get data "x" or "y" for example from "coordinates"? or "name" and "year" from "house"?
JSONParser parser = new JSONParser();
JSONArray a = (JSONArray) parser.parse(new FileReader("ff.json"));
for (Object o : a)
{
JSONObject person = (JSONObject) o;
JSONObject coor = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
Long id = (Long) person.get("id");
System.out.println(id);
Double area = (Double) person.get("area");
System.out.println(area);
Coordinates oor = (Coordinates) person.get("coordinates");
System.out.println(person.get("oor"));
I tried to do this but I get exception
"
flatFive
387
332.3
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to Coordinates"
I think using jackson for this would be a better approach. Something like this:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class Parse {
public static void main(String[] args) {
parse("{\n" + " \"id\":387,\n" + " \"name\":\"flatFive\",\n" + " \"coordinates\":{\n" + " \"x\":9.6,\n" + " \"y\":2.2\n" + " },\n" + " \"creationDate\":{\n" + " \"year\":2020,\n" + " \"monthValue\":4,\n" + " \"month\":\"APRIL\",\n" + " \"dayOfMonth\":1,\n" + " \"dayOfYear\":92,\n" + " \"dayOfWeek\":\"WEDNESDAY\",\n" + " \"hour\":20,\n" + " \"minute\":40,\n" + " \"second\":47,\n" + " \"nano\":662000000,\n" + " \"chronology\":{\n" + " \"id\":\"ISO\",\n" + " \"calendarType\":\"iso8601\"\n" + " }\n" + " },\n" + " \"area\":332.3,\n" + " \"numberOfRooms\":3,\n" + " \"furnish\":\"bad\",\n" + " \"view\":\"NORMAL\",\n" + " \"transport\":\"NONE\",\n" + " \"house\":{\n" + " \"name\":\"Cottage\",\n" + " \"year\":3,\n" + " \"numberOfLifts\":6\n" + " }\n" + "}");
}
public static void parse(String url) {
Destination destination = (Destination) convertBodyToObject(url, Destination.class);
System.out.println(destination.getId());
System.out.println(destination.getCoordinates().getX());
System.out.println(destination.getCoordinates().getY());
System.out.println(destination.getHouse().getName());
System.out.println(destination.getHouse().getYear());
}
public static Object convertBodyToObject(String body, Class object) {
try {
return new ObjectMapper().readValue(body, object);
} catch (JsonGenerationException e) {
System.out.println("JsonGenerationException - Failed to convertBodyToObject() " + e);
} catch (JsonMappingException e) {
System.out.println("JsonMappingException - Failed to convertBodyToObject() " + e);
} catch (IOException e) {
System.out.println("IOException - Failed to convertBodyToObject() " + e);
}
throw new RuntimeException("Terminating... " + body + " couldn't be mapped correctly");
}
}
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Destination {
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
private Coordinates coordinates;
private House house;
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public House getHouse() {
return house;
}
public void setHouse(House house) {
this.house = house;
}
}
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class House {
private String name;
private Integer year;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
}
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Coordinates {
private Double x;
private Double y;
public Double getX() {
return x;
}
public void setX(Double x) {
this.x = x;
}
public Double getY() {
return y;
}
public void setY(Double y) {
this.y = y;
}
}

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.

Categories

Resources