如何使用Gson将如下所示的JSON响应转换为POJO?

时间:2019-03-02 09:05:20

标签: json gson pojo

我的JSON格式为:

{"abc": [{
  "field_1": "string_1",
  "value": 0.304
},
{
  "field_1": "string_2",
  "value": 0.193
}]}

“ abc”是变量,“ field_1”和“ value”是字段名称。我想要一个Java类,以某种格式存储此JSON,例如:

 String t;                      // should store "abc"
 List<myClass> myClassObject;   // myClass should contain "field_1" and "value"

myClass.java

String field_1;              // should store "string_1" and "string_2"
Double value;                // should store 0.304 and 0.193

我想要类 myClass.java ,因为将来我可能想在JSON响应中添加更多元数据。这是复杂的对象映射,但是我无法弄清楚我的类应该如何存储JSON响应。

2 个答案:

答案 0 :(得分:0)

对于根对象,请勿使用POJO创建新的Map。示例可能如下所示:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public class GsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        Gson gson = new GsonBuilder().create();

        Type mapType = new TypeToken<Map<String, List<Item>>>() {
        }.getType();
        Map<String, List<Item>> map = gson.fromJson(new FileReader(jsonFile), mapType);
        Map.Entry<String, List<Item>> first = map.entrySet().stream().findFirst().get();
        Items items = new Items(first.getKey(), first.getValue());

        System.out.println(items);
    }
}

class Items {
    private final String key;
    private final List<Item> items;

    public Items(String key, List<Item> items) {
        this.key = key;
        this.items = items;
    }

    public String getKey() {
        return key;
    }

    public List<Item> getItems() {
        return items;
    }

    @Override
    public String toString() {
        return "Items{" +
                "key='" + key + '\'' +
                ", items=" + items +
                '}';
    }
}

class Item {

    @SerializedName("field_1")
    private String field;
    private Double value;

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public Double getValue() {
        return value;
    }

    public void setValue(Double value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Item{" +
                "field='" + field + '\'' +
                ", value=" + value +
                '}';
    }
}

上面的代码显示:

Items{key='abc', items=[Item{field='string_1', value=0.304}, Item{field='string_2', value=0.193}]}

答案 1 :(得分:0)

我正在向您分享示例代码:

主要方法:

import com.google.gson.Gson;
public class GsonConversion {
public static void main(String[] args) {
    String json = "{\"abc\": [{" + 
            "  \"field_1\": \"string_1\"," + 
            "  \"value\": 0.304" + 
            "}," + 
            "{" + 
            "  \"field_1\": \"string_2\"," + 
            "  \"value\": 0.193" + 
            "}]}";
    Gson gson = new Gson();
    Type mapType = new TypeToken<Map<String, List<Data>>>() {
        }.getType();
        Map<String, List<Data>> map = gson.fromJson(json, mapType);
        Model model= new Model();
        map.entrySet().stream().forEach(entry->{
            model.setT(entry.getKey());
            model.setAbc(entry.getValue());
        });
        System.out.println("Key:"+model.getT());
        model.getAbc().stream().forEach(x->{
            System.out.println("Field:"+x.getField_1()+" Value:"+x.getValue());
        });
   }
}

父模型对象: i)模型班

import java.util.ArrayList;

public class Model {
   private String t;
   private ArrayList<Data> abc = new ArrayList<>();

   public String getT() {
        return t;
   }

   public void setT(String t) {
       this.t = t;
   }

   public ArrayList<Data> getAbc() {
         return abc;
   }

   public void setAbc(ArrayList<Data> abc) {
       this.abc = abc;
   }
}

ii)数据类

public class Data {
   private String field_1;
   private Double value;

   public Data() {
   }

   public String getField_1() {
       return field_1;
   }

    public void setField_1(String field_1) {
       this.field_1 = field_1;
   }

    public Double getValue() {
       return value;
   }

   public void setValue(Double value) {
       this.value = value;
   }
}