使用gson将json字符串转换为POJO

时间:2015-05-13 02:33:40

标签: java android json gson

我正在使用gson将json转换为模型,反之亦然。

json String如下:

 {
"p": {
    "1": {
        "address": "asd",
        "name": "1",
        "dob": 1
    },
    "2": {
        "address": "asd",
        "name": "2",
        "dob": 1
    },
    "3": {
        "address": "asd",
        "name": "3",
        "dob": 1
    }
},
"as": "value"}

我的pojo课程如下:

package com.example.androtest;

public class Pojo {

String name, address;
int dob;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public int getDob() {
    return dob;
}

public void setDob(int dob) {
    this.dob = dob;
}

}

以下是模型类,要隐藏到模型中我创建了模型类ArrayList p getter setter

package com.example.androtest;
import java.util.ArrayList;

public class Listpojo {

    ArrayList<Pojo> p ;

    public ArrayList<Pojo> getP() {
        return p;
    }

    public void setP(ArrayList<Pojo> p) {
        this.p = p;
    }


}

使用此转换:

String re = "{\"p\": {\"1\": {\"address\": \"asd\",\"name\": \"1\",\"dob\": 1},\"2\": {\"address\": \"asd\",\"name\": \"2\"dob\": 1},\"3\": {\"address\": \"asd\",\"name\": \"3\", \"dob\": 1}}}";

Listpojo ps = CoreGsonUtils.fromJson(re, Listpojo.class);

但它不是在说,任何人都可以告诉我如何转换它吗?

1 个答案:

答案 0 :(得分:1)

如果你想要这样的东西(你遗漏了as):

class ListPojo{
  ArrayList<Pojo> p;
  String as;
}

然后json应该是:

{
"p": [
  {
    "address": "asd",
    "name": "1",
    "dob": 1
  },
  {
    "address": "asd",
    "name": "2",
    "dob": 1
  },
  {
    "address": "asd",
    "name": "3",
    "dob": 1
  }
],
"as": "value"
}

上述解决方案假设p是ArrayList。但如果它是一张地图,那么原来的json就可以了,你只需要用

替换p
class ListPojo{
   Map<Integer, Pojo> p;
   String as;
}