0

i have Json String ,which looks like this

String RET=[{"id":"1","name":"koukouvagia","category":"c","lat":"35.52563370000000","lon":"24.05584680000000","address":"Alexi Minoti","phone":"2821027449","counter":"0"},{"id":"2","name":"theatro","category":"c","lat":"35.51392000000000","lon":"24.01979000000000","address":"Plateia Agoras 69","phone":"2821008500","counter":"0"},{"id":"3","name":"mikro kafe","category":"c","lat":"35.51700560000000","lon":"24.02495420000000","address":"Akth Miaouli 6","phone":"2821059321","counter":"0"},{"id":"4","name":"mikro efeteio","category":"c","lat":"35.51033020000000","lon":"24.03102900000000","address":"Plateia Dikastirion","phone":"2821028112","counter":"0"},{"id":"5","name":"Grhgorhs","category":"c","lat":"35.51355300000000","lon":"24.02024900000000","address":"N.Plasthra \u0026 S.Venizelou","phone":"0","counter":"0"}]

and want to convert this Json string to arraylist of Objects and put all the elements on a class (Data Object.class) and print the elements.

    Type listOfTestObject=new TypeToken<List<DataObject>>(){}.getType();
    List<DataObject> list2 = g.fromJson(RET, listOfTestObject);

     for(int i = 0; i < list2.size(); i++) {
            System.out.println(list2.get(i).getNameF());
        }

the output is:

null
null
null
null
null

the class that i create has that form

public class DataObject {
  String idF;
  String nameF;
  String categoryF;
  String latF;
  String lonF;
  String addressF;
  String phoneF;
  String counterF;


public String getIdF() {
    return idF;
}
public void setIdF(String idF) {
    this.idF = idF;
}
public String getNameF() {
    return nameF;
}
public void setNameF(String nameF) {
    this.nameF = nameF;}

.
.
.

}

what i am doing wrong?

Oban
  • 11
  • 2

2 Answers2

1

All you have to do to fix it is to add annotation to every field:

@SerializedName("id")
String idF;
@SerializedName("name")
String nameF;
Ravi
  • 30,829
  • 42
  • 119
  • 173
Ruslan Ostafiichuk
  • 4,422
  • 6
  • 30
  • 35
0

List< DataObject> is the same type as just List. For array parsing you should write next:

List<DataObject> list2 = new ArrayList<DataObject>((DataObject[])g.fromJson(RET, DataObject[]));

for(int i = 0; i < list2.size(); i++) {
        System.out.println(list2.get(i).getNameF());
}

And also you should explain for parser, what field is connected to what JSON parameter. If you use GSON parser, you can write annotations. Or for jackson you should rename your getters and setter, as it was told you in the comments.

Annotations should look next:

class DataObject {
  @SerializedName("id")
  String idF;
}

and write in brackets field name in JSON string

Orest Savchak
  • 4,529
  • 1
  • 18
  • 27