如何使用杰克逊将JSON字符串解析为Java对象? [英] How to parse JSON String to java object with jackson?

查看:106
本文介绍了如何使用杰克逊将JSON字符串解析为Java对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在尝试将此VCAP_SERVICES解析为Java对象时遇到麻烦.我不太了解如何构造POJO,以使其能够映射json字符串中的值.有人可以帮我构造我的pojo,使其与json字符串对齐吗?

I am currently having trouble trying to parse this VCAP_SERVICES to java objects. I do not quite understand how to structure the POJO to allow it to map the values from the json string. Can someone please help me structure my pojo so that it is aligns with the json string?

我想为两个凭证创建对象:accessToken ... jdbcurl.

I want to create objects for both of the credentials: accessToken... jdbcurl.

VCAP_SERVICES

   "VCAP_SERVICES": {
      "user-provided": [
        {
          "credentials": {
            "accessTokenUri": "tokenurl",
            "apiUrl": "apiurl",
            "clientId": "typeofID",
            "clientSecret": "secretAf",
            "scope": "none"
          },
          "syslog_drain_url": "",
          "volume_mounts": [],
          "label": "user-provided",
          "name": "OAuth2",
          "tags": []
        },
        {
          "credentials": {
            "jdbcUrl": "jdbc:oracle:connection[host]:[port]/service",
            "spring.datasource.driver-class-name": "oracle.jdbc.OracleDriver",
            "spring.datasource.initialize": "false"
          },
          "syslog_drain_url": "",
          "volume_mounts": [],
          "label": "user-provided",
          "name": "Database",
          "tags": []
        }
      ]

Java类

ObjectMapper mapper = new ObjectMapper();
        //json String to Object

CupsProperties properties = mapper.readValue(VCAP_Services, CupsProperties.class);

System.out.println(properties.getJdbcUrl() + "!!!!!!!!!!!!!!!!!!!");

POJOS

public class UserProviderWrapper {

    @JsonProperty("user-provided")
    public List<CupsProperties> cupsProperties;
    @JsonProperty("syslog_drain_url")
    public String syslog_drain_url;
    @JsonProperty("volume_mounts")
    public List<String> volume_mounts;
    @JsonProperty("label")
    public String label;
    @JsonProperty("name")
    public String name;
    @JsonProperty("tags")
    public List<String> tags;
      //getters and setters


public class CupsProperties {

    @JsonProperty("jdbcUrl")
    public String jdbcUrl;
    @JsonProperty("spring.datasource.driver-class-name")
    public String driver;
    @JsonProperty("spring.datasource.initialize")
    public String initialize;
   //getters and setters

错误

无法识别的字段用户提供"(类rest.springframework.model.CupsProperties),未标记为可忽略(2个已知属性:"jdbcUrl","dataSource"]) 在[来源:{用户提供":[{凭证":{"jdbcUrl":"jdbc:oracle:thin:user/pass//host:port/service","spring.datasource.driver-class- name:" oracle.jdbc.OracleDriver," spring.datasource.initialize:" false}," syslog_drain_url:"," volume_mounts:[]," label:"用户提供,"名称:" Oracle,"标签:[]}]};第1行,第19列](通过参考链:rest.springframework.model.CupsProperties [用户提供"])

Unrecognized field "user-provided" (class rest.springframework.model.CupsProperties), not marked as ignorable (2 known properties: "jdbcUrl", "dataSource"]) at [Source: {"user-provided":[{ "credentials": { "jdbcUrl": "jdbc:oracle:thin:user/pass//host:port/service", "spring.datasource.driver-class-name": "oracle.jdbc.OracleDriver", "spring.datasource.initialize": "false" }, "syslog_drain_url": "", "volume_mounts": [ ], "label": "user-provided", "name": "Oracle", "tags": [ ] }]}; line: 1, column: 19] (through reference chain: rest.springframework.model.CupsProperties["user-provided"])

推荐答案

检查以下解决方案,看它是否满足您的需求.如果需要解析更多字段,则可以在此基础上构建.

Check below solution and see if it fulfills your need. You can build on to it if you need to parse more fields.

import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JsonParser {

    public static void main(String[] args) {

        String VCAP_Services = "{\"userProvided\": [{\"credentials\": {\"accessTokenUri\": \"tokenurl\",\"apiUrl\": \"apiurl\",\"clientId\": \"typeofID\",\"clientSecret\": \"secretAf\",\"scope\": \"none\"},\"syslog_drain_url\": \"\",\"volume_mounts\": [],\"label\": \"user-provided\",\"name\": \"OAuth2\",\"tags\": []},{\"credentials\": {\"jdbcUrl\": \"jdbc:oracle:connection[host]:[port]/service\",\"spring.datasource.driver-class-name\": \"oracle.jdbc.OracleDriver\",\"spring.datasource.initialize\": \"false\"},\"syslog_drain_url\": \"\",\"volume_mounts\": [],\"label\": \"user-provided\",\"name\": \"Database\",\"tags\": [] } ] } ";

        CupsProperties properties=null;
        try {

            JSONParser jsonParser = new JSONParser();
            JSONObject vcapServiceJSONObject = (JSONObject) jsonParser.parse(VCAP_Services);

            for(Object key: vcapServiceJSONObject.keySet()){
                String keyStr = (String) key;
                JSONArray userProvidedList = (JSONArray) vcapServiceJSONObject.get(keyStr);

                Iterator i = userProvidedList.iterator();
                while (i.hasNext()) {
                    JSONObject innerObj = (JSONObject) i.next();
                    JSONObject credentialsObject = (JSONObject) innerObj.get("credentials");
                    if(credentialsObject.containsKey("jdbcUrl")){
                        //set to your pojo objects
                        System.out.println("JDBC url:" + credentialsObject.get("jdbcUrl"));
                    }

                    if(credentialsObject.containsKey("accessTokenUri")){
                        //set to your pojo objects
                        System.out.println("Access token URI:" + credentialsObject.get("accessTokenUri"));
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

输出

Access token URI:tokenurl
JDBC url:jdbc:oracle:connection[host]:[port]/service

这篇关于如何使用杰克逊将JSON字符串解析为Java对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆