java json字符串到对象的arraylist

时间:2014-11-20 15:42:53

标签: java json arraylist

我有Json String,看起来像这样

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"}]

并希望将此Json字符串转换为Objects的arraylist并将所有元素放在类(Data Object.class)上并打印元素。

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

输出是:

null
null
null
null
null

我创建的类具有该表单

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

.
.
.

}

我做错了什么?

2 个答案:

答案 0 :(得分:1)

要解决这个问题,您需要做的就是为每个字段添加注释:

@SerializedName("id")
String idF;
@SerializedName("name")
String nameF;

答案 1 :(得分:0)

列表与LT;数据对象&GT;是与List相同的类型。对于数组解析,您应该编写下一个:

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

你也应该解释一下解析器,哪个字段连接到什么JSON参数。如果使用GSON解析器,则可以编写注释。或者对杰克逊来说,你应该重新命名你的getter和setter,就像在评论中告诉你的那样。

接下来应该注释:

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

并在JSON字符串

中的括号字段名称中写入