JSON对象提取值

时间:2014-11-11 08:12:42

标签: java json parsing jackson

我有这个代码,它以JSON Object的格式从API提供程序返回响应。以下是代码:

public class Authentication {   
    public static void main(String[] args) {
        try {
            URL url = new URL ("https://xxxxx.com");
            String encoding = "xxxxxxxxx";
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty  ("Authorization", "Basic " + encoding);
            InputStream content = (InputStream)connection.getInputStream();
            BufferedReader in   = 
                new BufferedReader (new InputStreamReader (content));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);                                                
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

以上代码将返回如下响应:

{
  "accessToken": "0.AQAAAUmdztB3AAAAAAAEkvg",
  "tokenType": "Bearer",
  "expiresIn": 300
}

所以这就是问题所在,我只是试图获取accessToken的值,以便我可以使用它来进行api调用。我试过这个:

String loudScreaming = JSONML.toJSONObject("accessToken").getString("accessToken"); 

但它将返回null。我读过有关杰克逊的内容,但对如何做到这一点并不知情。请指导我。提前谢谢。

2 个答案:

答案 0 :(得分:1)

您不需要Jackson解析简单的JSON结构。这将完成工作

import org.json.JSONObject;

String jsondata = "{\"accessToken\":\"0.AQAAAUmdztB3AAAAAAAEkvg\",\"tokenType\":\"Bearer\",\"expiresIn\": 300}"

JSONObject obj = new JSONObject(jsondata);
String accessToken = obj.getJSONObject().getString("accessToken");

答案 1 :(得分:0)

以下是几个简单的示例,展示了如何使用 Jackson (版本2.4.3)以及如何使用 GSON (版本2.3)。这些是非常基本的用例,它们的文档显示了这些库的多样性。

final String JSON_STRING = "{\n" +
        "  \"accessToken\": \"0.AQAAAUmdztB3AAAAAAAEkvg\",\n" +
        "  \"tokenType\": \"Bearer\",\n" +
        "  \"expiresIn\": 300\n" +
        "}";
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode jackson = objectMapper.readValue(JSON_STRING, ObjectNode.class);
JsonNode jacksonAccessToken = jackson.get("accessToken");
System.out.println("Jackson accessToken: " + jacksonAccessToken);

Gson gson = new Gson();
JsonObject gsonObject = gson.fromJson(JSON_STRING, JsonObject.class);
JsonElement gsonAccessToken = gsonObject.get("accessToken");
System.out.println("GSON accessToken: " + jacksonAccessToken);