如何将字符串转换为Json / maps

时间:2018-12-09 11:29:59

标签: java json maps

我想将下面的字符串转换为json或映射以读取单个消息,所以我该如何实现。

 {
  "import_set"XXXX00123",
  "staging_table": "u_xx_imp_set_xxx_yyy",
  "result": [
    {
      "transform_map": "EE Trsfrm test ",
      "status": "error",
      "error_message": "Unable to resolve ",
      "status_message": "Unable to resolve target record"
    }
  ]
}

我要在这里阅读statuserror_message等。

2 个答案:

答案 0 :(得分:0)

您可以使用ObjectMapper或Gson。 ObjectMapper代码将字符串解析为Map:

private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
Map<String, Object> map = OBJECT_MAPPER.readValue("jsonString",
            new TypeReference<Map<String, Object>>() {})

Gson代码:

Gson gson = new Gson();
Map<String, Object> myMap = gson.fromJson("jsonString", 
  new TypeReference<Map<String, Object>>() {}.getType());

答案 1 :(得分:0)

有很多库可让您解析JSON。最受欢迎的两个大概是GsonJackson。这是使用它们将字符串解析为JSON节点的示例。

Gson

public static void main(String[] args) {
    final JsonParser parser = new JsonParser();
    final JsonObject jsonObject = parser.parse("{ \"import_set\": \"ISET0010118\", \"staging_table\": \"u_ee_imp_set_asset_nmi\", " +
                                               "\"result\": [{ \"transform_map\": \"EE Trsfrm Map Asset NMI \", \"status\": " +
                                               "\"error\", \"error_message\": \"Unable to resolve target record, coalesce values not " +
                                               "present: u_assetid; Invalid table \", \"status_message\": \"Unable to resolve target " +
                                               "record, coalesce values not present: u_assetid\" }] }").getAsJsonObject();

    System.out.println(jsonObject);
    System.out.println(jsonObject.get("result").getAsJsonArray().get(0).getAsJsonObject().get("status").getAsString());
    System.out.println(jsonObject.get("result").getAsJsonArray().get(0).getAsJsonObject().get("error_message").getAsString());
}

杰克逊

public static void main(String[] args) throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode jsonNode = mapper.readTree("{ \"import_set\": \"ISET0010118\", \"staging_table\": \"u_ee_imp_set_asset_nmi\", " +
                                              "\"result\": [{ " +
                                              "\"transform_map\": \"EE Trsfrm Map Asset NMI \", \"status\": \"error\", " +
                                              "\"error_message\": \"Unable to resolve " +
                                              "target record, coalesce values not present: u_assetid; Invalid table \", " +
                                              "\"status_message\": \"Unable to resolve" +
                                              " target record, coalesce values not present: u_assetid\" }] }");

    System.out.println(jsonNode);
    System.out.println(jsonNode.get("result").get(0).get("status").asText());
    System.out.println(jsonNode.get("result").get(0).get("error_message").asText());
}

两个示例都将打印:

{"import_set":"ISET0010118","staging_table":"u_ee_imp_set_asset_nmi","result":[{"transform_map":"EE Trsfrm Map Asset NMI ","status":"error","error_message":"Unable to resolve target record, coalesce values not present: u_assetid; Invalid table ","status_message":"Unable to resolve target record, coalesce values not present: u_assetid"}]}
error
Unable to resolve target record, coalesce values not present: u_assetid; Invalid table 

或者您可以创建一个POJO来托管您的数据并将字符串直接解析为objests:

Gson

public class Demo {
    public static void main(String[] args) throws IOException {
        final Gson gson = new Gson();
        final Results results = gson.fromJson("{ \"import_set\": \"ISET0010118\", \"staging_table\": \"u_ee_imp_set_asset_nmi\", " +
                                              "\"result\": [{ " +
                                              "\"transform_map\": \"EE Trsfrm Map Asset NMI \", \"status\": \"error\", " +
                                              "\"error_message\": \"Unable to resolve " +
                                              "target record, coalesce values not present: u_assetid; Invalid table \", " +
                                              "\"status_message\": \"Unable to resolve" +
                                              " target record, coalesce values not present: u_assetid\" }] }", Results.class);

        System.out.println(results.getResult().get(0).getStatus());
        System.out.println(results.getResult().get(0).getErrorMessage());
    }
}

class Results {
    @SerializedName("import_set")
    private String importSet;
    @SerializedName("staging_table")
    private String stagingTable;
    @SerializedName("result")
    private List<Result> result;

    public String getImportSet() {
        return importSet;
    }

    public void setImportSet(String importSet) {
        this.importSet = importSet;
    }

    public String getStagingTable() {
        return stagingTable;
    }

    public void setStagingTable(String stagingTable) {
        this.stagingTable = stagingTable;
    }

    public List<Result> getResult() {
        return result;
    }

    public void setResult(List<Result> result) {
        this.result = result;
    }
}

class Result {
    @SerializedName("transform_map")
    private String transformMap;
    @SerializedName("status")
    private String status;
    @SerializedName("error_message")
    private String errorMessage;
    @SerializedName("status_message")
    private String statusMessage;

    public String getTransformMap() {
        return transformMap;
    }

    public void setTransformMap(String transformMap) {
        this.transformMap = transformMap;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getStatusMessage() {
        return statusMessage;
    }

    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }
}

杰克逊

public class Demo {
    public static void main(String[] args) throws IOException {
        final ObjectMapper mapper = new ObjectMapper();
        final Results results = mapper.readValue("{ \"import_set\": \"ISET0010118\", \"staging_table\": \"u_ee_imp_set_asset_nmi\", " +
                                                 "\"result\": [{ " +
                                                 "\"transform_map\": \"EE Trsfrm Map Asset NMI \", \"status\": \"error\", " +
                                                 "\"error_message\": \"Unable to resolve " +
                                                 "target record, coalesce values not present: u_assetid; Invalid table \", " +
                                                 "\"status_message\": \"Unable to resolve" +
                                                 " target record, coalesce values not present: u_assetid\" }] }", Results.class);

        System.out.println(results.getResult().get(0).getStatus());
        System.out.println(results.getResult().get(0).getErrorMessage());
    }
}

class Results {
    @JsonProperty("import_set")
    private String importSet;
    @JsonProperty("staging_table")
    private String stagingTable;
    @JsonProperty("result")
    private List<Result> result;

    public String getImportSet() {
        return importSet;
    }

    public void setImportSet(String importSet) {
        this.importSet = importSet;
    }

    public String getStagingTable() {
        return stagingTable;
    }

    public void setStagingTable(String stagingTable) {
        this.stagingTable = stagingTable;
    }

    public List<Result> getResult() {
        return result;
    }

    public void setResult(List<Result> result) {
        this.result = result;
    }
}

class Result {
    @JsonProperty("transform_map")
    private String transformMap;
    @JsonProperty("status")
    private String status;
    @JsonProperty("error_message")
    private String errorMessage;
    @JsonProperty("status_message")
    private String statusMessage;

    public String getTransformMap() {
        return transformMap;
    }

    public void setTransformMap(String transformMap) {
        this.transformMap = transformMap;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getStatusMessage() {
        return statusMessage;
    }

    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }
}

如您所见,Gson和Jackson十分相似,并且在注解和方法名称上大多不同,但是原理是相同的。