如何使用jackson将JSON String解析为java对象?

时间:2017-05-01 19:09:17

标签: java json parsing

我目前在尝试将此VCAP_SERVICES解析为java对象时遇到问题。我不太了解如何构造POJO以允许它映射json字符串中的值。有人可以帮我构建我的pojo,以便它与json字符串对齐吗?

我想为两个凭据创建对象: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() + "!!!!!!!!!!!!!!!!!!!");

POJO。

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

错误

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

1 个答案:

答案 0 :(得分:1)

检查以下解决方案,看看它是否满足您的需求。如果需要解析更多字段,可以继续使用它。

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