如何从REST API中的Json数组中获取JSON对象

时间:2016-05-27 07:21:48

标签: java json

我是REST API的新手,在我们的自动化脚本中处理JSON。我有一个API,其响应为JSONArray,即

[{"ProjectID":15,"ProjectName":" Securities"},{"ProjectID":16,"ProjectName":"PAS "}]

虽然自动化,但为了验证,我需要获取响应。我已经尝试过以下但没有得到预期的输出

 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.Scanner;
 import org.json.*;

 public class ProjectNameVerfication {

 public static void main(String[] args) throws JSONException
 {

  try 
  {
    URL url = new URL("http://17*.**.**.**:3000/api/******");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json");

    if (conn.getResponseCode() != 200) 
    {
       throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
    }

    Scanner scan = new Scanner(url.openStream());
    String str = new String();
    while (scan.hasNext())
       str += scan.nextLine();
    scan.close();

    System.out.println("str : " + str);

    JSONObject obj = new JSONObject(str.substring(str.indexOf('{')));
    System.out.println("obj : " +obj);
    int ProjectID = obj.optInt("ProjectID");
    String ProjectName = obj.getString("ProjectName");

    System.out.println("ProjectID: " +ProjectID);
    System.out.println("ProjectName: " +ProjectName);

    JSONArray arr = obj.getJSONArray("ProjectID");
    for (int i = 0; i < arr.length(); i++)
    {
      String post_id =arr.getJSONObject(i).getString("ProjectName");
    }

    conn.disconnect();
  }
  catch (MalformedURLException e) { e.printStackTrace();}
  catch (IOException e) { e.printStackTrace(); }

 }
}

实际输出如下:

str : [{"ProjectID":15,"ProjectName":" Securities"},{"ProjectID":16,"ProjectName":"PAS "}]

obj : {"ProjectName":" securities""ProjectID":15}

ProjectID: 15
ProjectName:  Securities

Exception in thread "main" org.json.JSONException: JSONObject["ProjectID"] is not a JSONArray.
    at org.json.JSONObject.getJSONArray(JSONObject.java:539)
    at MyTest.ProjectNameVerfication.main(ProjectNameVerfication.java:60)

3 个答案:

答案 0 :(得分:0)

你想获得所有JSONArray,对吧?

查看您的回复数据:

JSONArray

它已经是ProjectName字符串,您可以将其解析为foreach,并在 JSONArray jsonArray = new JSONArray("your str"); for (Object object : jsonArray) { JSONObject jsonObject = (JSONObject)object; System.out.println(jsonObject.toString()); } 中获取 function initPushwoosh() { var pushNotification = cordova.require("pushwoosh-cordova-plugin.PushNotification"); //set push notifications handler document.addEventListener('push-notification', function(event) { var title = event.notification.title; var userData = event.notification.userdata; if(typeof(userData) != "undefined") { console.warn('user data: ' + JSON.stringify(userData)); } alert(title); }); //initialize Pushwoosh with projectid: "GOOGLE_PROJECT_NUMBER", pw_appid : "PUSHWOOSH_APP_ID". This will trigger all pending push notifications on start. pushNotification.onDeviceReady({ projectid: "XXXXXXXXX", pw_appid : "XXXXXXXX" }); //register for pushes pushNotification.registerDevice( function(status) { var pushToken = status; console.warn('push token: ' + pushToken); }, function(status) { console.warn(JSON.stringify(['failed to register ', status])); } ); }

Uncaught ReferenceError: cordova is not defined

答案 1 :(得分:0)

您的回复是一个数组,因此您需要JSONArray而不是JSONObject

    try {

        JSONArray e = new JSONArray(str);
        int l = e.length();

        for (int x = 0; x < l; x++) {
            JSONObject object1 = e.getJSONObject(x);
            String projectID = object1.getString("ProjectID");
            String projectName = object1.getString("ProjectName");
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

答案 2 :(得分:-1)

如果您使用简单JSON ,则必须按如下方式解析。

String str =“[{\”ProjectID \“:15,\”ProjectName \“:\”Securities \“}, {\“ProjectID \”:16,\“ProjectName \”:\“PAS \”}]“;

        JSONParser json=new JSONParser();
        try {
        JSONArray   arr=(JSONArray)json.parse(str);         
        for (int i = 0; i < arr.size(); i++) {
            JSONObject obj=(JSONObject)arr.get(i); 
            System.out.println("ProjectID: "+obj.get("ProjectID"));
            System.out.println("ProjectName: "+obj.get("ProjectName"));
        } 
        } catch (ParseException e) {                
            e.printStackTrace();
        }