【问题标题】:Parsing JSON in java - how to get String or JsonObject from json file property(value - json object) using POJO only在 java 中解析 JSON - 如何仅使用 POJO 从 json 文件属性(值 - json 对象)中获取 String 或 JsonObject
【发布时间】:2019-02-21 00:05:36
【问题描述】:

json结构如下:

{
  "key":"Key",
  "value":{
  "first": "first",
  "second": "second"
  }
}

我想使用 Spring Boot 将此 json 作为 Plain Old Java Object

public class File {
    private String key;
    private JsonObject value;

    public File(String key, JsonObject value) {
        this.key = key;
        this.value = value;
    }

    public File() {
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public JsonObject getValue() {
        return value;
    }

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

JsonObject - lib com.google.gson中的类
我得到{}

将字段“值”作为 String 是完美的,但 JsonObject 也可以。

【问题讨论】:

    标签: java json parsing gson


    【解决方案1】:

    完成! com.google.json lib 使用 setter 是可能的:

    public class File {
        private String key;
        private String value;
    
        public File() {
        }
    
        public String getKey() {
            return key;
        }
    
        public void setKey(String key) {
            this.key = key;
        }
    
        public String getValue() {
            return value;
        }
    
        public void setValue(Object value) {
            this.value = new Gson().toJson(value);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-14
      相关资源
      最近更新 更多