有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中解析JSON响应以提取值

我想做的是得到一个响应,但不知道如何从中提取值

实际反应如下:

[
   "SUCCESS",
   [   [
      "Karachi",
      ["کراچی"],
      [],
            {
         "candidate_type": [0],
         "is_confident": [true]
      }
   ]]
]

我需要从中提取urdu文本

    String text = "Karachi";            
    String url = "https://inputtools.google.com/request";       
    try {           
         final HttpClient client = new HttpClient();
            final PostMethod method = new PostMethod(url);
            method.setParameter("text", text);
            method.setParameter("itc", "ur-t-i0-und");
            method.setParameter("num", "1");
            method.setParameter("cp", "0");
            method.setParameter("cs", "1");
            method.setParameter("ie", "utf-8");     
            client.executeMethod(method);               
            BufferedReader strResponse =  new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(),"UTF-8"));
            Object jObj =   (Object) JSON.parse(strResponse);

共 (2) 个答案

  1. # 1 楼答案

    我创建了一个适用于所有JSON的包装器:

    package com.myProject.SampleProject;
    
    import org.codehaus.jackson.JsonNode;
    import org.codehaus.jackson.map.ObjectMapper;
    import org.json.JSONObject;
    
    
    /**
    * These two dependences will require to use the code
    <dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
    </dependency>
    <dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160212</version>
    </dependency>
    */
    public class JsonExtractor {
    
    public static void main(String[] args) {
    
    
            String json = "{\r\n" + 
                    "  \"releases\": [\r\n" + 
                    "    {\r\n" + 
                    "      \"release_key\": \"e99e39b\",\r\n" + 
                    "      \"ship_advice_no\": \"313456\",\r\n" + 
                    "      \"source_node_id\": \"1\",\r\n" + 
                    "      \"source_node_type\": \"\",\r\n" + 
                    "      \"level_of_service\": \"\",\r\n" + 
                    "      \"fulfillment_quantities\": [\r\n" + 
                    "        {\r\n" + 
                    "          \"fulfillment_key\": null,\r\n" + 
                    "          \"order_line_key\": \"201807\",\r\n" + 
                    "          \"order_line_quantity\": \"1.0\"\r\n" + 
                    "        }\r\n" + 
                    "      ]\r\n" + 
                    "    },\r\n" + 
                    "    {\r\n" + 
                    "      \"release_key\": \"e9b4f604\",\r\n" + 
                    "      \"ship_advice_no\": \"3193457\",\r\n" + 
                    "      \"source_node_id\": \"\",\r\n" + 
                    "      \"source_node_type\": \"\",\r\n" + 
                    "      \"level_of_service\": \"\",\r\n" + 
                    "      \"fulfillment_quantities\": [\r\n" + 
                    "        {\r\n" + 
                    "          \"fulfillment_key\": null,\r\n" + 
                    "          \"order_line_key\": \"2018070\",\r\n" + 
                    "          \"order_line_quantity\": \"1.0\"\r\n" + 
                    "        }\r\n" + 
                    "      ]\r\n" + 
                    "    }\r\n" + 
                    "  ]\r\n" + 
                    "}";
            String print = getvalueThroughUrl(json, "/releases/[0]/release_key");
            System.out.println(print);
            print = getvalueThroughUrl(json, "/releases/[0]/fulfillment_quantities/[0]/order_line_quantity");
            System.out.println(print);
            print = getvalueThroughUrl(json, "/releases/[0]/ship_advice_no");
            System.out.println(print);
            print = getvalueThroughUrl(json, "/releases/[1]/fulfillment_quantities/[0]/order_line_key");
            System.out.println(print);
            print = getvalueThroughUrl(json, "/releases/[1]/release_key");
    
        }
    
    
        private static String[] getXpathOrder(String url) {
            String[] xpathOrder =  null;
            if(url.contains("&")) {
                xpathOrder = url.split("&");
            }
            else {
            xpathOrder = url.split("/");
            }
            return xpathOrder;
        }
    
    
        public static String getvalueThroughUrl(String json, String url) {
            String value = "";
            String[] xpathOrder =  getXpathOrder(url);
            JsonNode rootNode = null;
            String key = "";
            try {
            ObjectMapper objectMapper = new ObjectMapper();
            JSONObject jsonObject = new JSONObject(json);
            byte[] jsonData = jsonObject.toString().getBytes();
    //      JsonNode rootNode = objectMapper.readTree(jsonData);
    //      rootNode = objectMapper.readTree(jsonData);
            rootNode = objectMapper.readTree(jsonObject.toString());
            }catch(Exception e) {
                e.printStackTrace();
            }
            try {
            JsonNode node = null;
            for(int i=1;i<xpathOrder.length;i++) {
                if(node==null)
                    node = rootNode;
                if(xpathOrder[i].contains("[")){
                    xpathOrder[i] = xpathOrder[i].replace("[", "");
                    xpathOrder[i] = xpathOrder[i].replace("]", "");
                    node = node.get(Integer.parseInt(xpathOrder[i]));
                }
                else
                    node = node.path(xpathOrder[i]);
                    key = xpathOrder[i];
            }
            value = node.asText();
            }catch(Exception e) {
                e.printStackTrace();
            }
            System.out.println("API key: "+key+" value is:"+value);
            return value;
        }
    
    
    }
    
  2. # 2 楼答案

    试试这个(你的缓冲区读卡器可能不止一行):

    StringBuilder yourJsonString= new StringBuilder();
    String line;
    while ((line = strResponse.readLine()) != null) {
          yourJsonString.append(line);
    }
    JSONArray jsonObject = new JSONArray(yourJsonString.toString());
    //retrieve the second element of json array
    JSONArray secondElmArray= jsonObject.getJSONArray(1);
    JSONArray innerArray = secondElmArray.getJSONArray(0);
    
    JSONArray urduList= innerArray.getJSONArray(1);
    String urduWord= urduList.getString(0);