简体   繁体   中英

convert json string to POJO using gson

I am using gson to convert json to model and vice-versa .

json String is as follow:

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

My pojo class is as follow :

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

}

And following is the model class ,to covert into model I have created model class 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;
    }


}

Using this to convert:

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

but its not woking ,Can any one let me know how i can convert it ?

If you want to have something something like this (you left out as ):

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

Then the json should be:

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

The above solution is assuming that p is an ArrayList. But if it's a Map then the original json would be fine and you just need to replace p with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM