Java 从URL解析JSON

Java 从URL解析JSON,java,json,url,Java,Json,Url,有没有从URL解析JSON的最简单方法?我使用了Gson,但找不到任何有用的例子 首先,您需要下载URL(作为文本): private static String readUrl(String urlString) throws Exception { BufferedReader reader = null; try { URL url = new URL(urlString); reader = new BufferedReader(new I

有没有从URL解析JSON的最简单方法?我使用了Gson,但找不到任何有用的例子

  • 首先,您需要下载URL(作为文本):

    private static String readUrl(String urlString) throws Exception {
        BufferedReader reader = null;
        try {
            URL url = new URL(urlString);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read); 
    
            return buffer.toString();
        } finally {
            if (reader != null)
                reader.close();
        }
    }
    
    static class Item {
        String title;
        String link;
        String description;
    }
    
    static class Page {
        String title;
        String link;
        String description;
        String language;
        List<Item> items;
    }
    
    public static void main(String[] args) throws Exception {
    
        String json = readUrl("http://www.javascriptkit.com/"
                              + "dhtmltutors/javascriptkit.json");
    
        Gson gson = new Gson();        
        Page page = gson.fromJson(json, Page.class);
    
        System.out.println(page.title);
        for (Item item : page.items)
            System.out.println("    " + item.title);
    }
    
    try {
        JSONObject json = new JSONObject(readUrl("..."));
    
        String title = (String) json.get("title");
        ...
    
    } catch (JSONException e) {
        e.printStackTrace();
    }
    
  • 然后需要解析它(这里有一些选项)。

    • GSON(完整示例):

      private static String readUrl(String urlString) throws Exception {
          BufferedReader reader = null;
          try {
              URL url = new URL(urlString);
              reader = new BufferedReader(new InputStreamReader(url.openStream()));
              StringBuffer buffer = new StringBuffer();
              int read;
              char[] chars = new char[1024];
              while ((read = reader.read(chars)) != -1)
                  buffer.append(chars, 0, read); 
      
              return buffer.toString();
          } finally {
              if (reader != null)
                  reader.close();
          }
      }
      
      static class Item {
          String title;
          String link;
          String description;
      }
      
      static class Page {
          String title;
          String link;
          String description;
          String language;
          List<Item> items;
      }
      
      public static void main(String[] args) throws Exception {
      
          String json = readUrl("http://www.javascriptkit.com/"
                                + "dhtmltutors/javascriptkit.json");
      
          Gson gson = new Gson();        
          Page page = gson.fromJson(json, Page.class);
      
          System.out.println(page.title);
          for (Item item : page.items)
              System.out.println("    " + item.title);
      }
      
      try {
          JSONObject json = new JSONObject(readUrl("..."));
      
          String title = (String) json.get("title");
          ...
      
      } catch (JSONException e) {
          e.printStackTrace();
      }
      
    • 从以下位置尝试java API:

      private static String readUrl(String urlString) throws Exception {
          BufferedReader reader = null;
          try {
              URL url = new URL(urlString);
              reader = new BufferedReader(new InputStreamReader(url.openStream()));
              StringBuffer buffer = new StringBuffer();
              int read;
              char[] chars = new char[1024];
              while ((read = reader.read(chars)) != -1)
                  buffer.append(chars, 0, read); 
      
              return buffer.toString();
          } finally {
              if (reader != null)
                  reader.close();
          }
      }
      
      static class Item {
          String title;
          String link;
          String description;
      }
      
      static class Page {
          String title;
          String link;
          String description;
          String language;
          List<Item> items;
      }
      
      public static void main(String[] args) throws Exception {
      
          String json = readUrl("http://www.javascriptkit.com/"
                                + "dhtmltutors/javascriptkit.json");
      
          Gson gson = new Gson();        
          Page page = gson.fromJson(json, Page.class);
      
          System.out.println(page.title);
          for (Item item : page.items)
              System.out.println("    " + item.title);
      }
      
      try {
          JSONObject json = new JSONObject(readUrl("..."));
      
          String title = (String) json.get("title");
          ...
      
      } catch (JSONException e) {
          e.printStackTrace();
      }
      

  • 您可以使用org.apache.commons.io.IOUtils进行下载,使用org.json.JSONTokener进行解析:

    JSONObject jo = (JSONObject) new JSONTokener(IOUtils.toString(new URL("http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json"))).nextValue();
    System.out.println(jo.getString("version"));
    
    这里有一个简单的方法

    首先从url解析JSON-

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
    
        try {
    
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
    
            if (statusCode == 200) {
    
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
    
                inputStream.close();
    
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }
    
    然后放置一个任务,然后从JSON读取所需的值-

    private class ReadPlacesFeedTask extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... urls) {
    
            return readJSONFeed(urls[0]);
        }
    
        protected void onPostExecute(String result) {
    
            JSONObject json;
            try {
                json = new JSONObject(result);
    
            ////CREATE A JSON OBJECT////
    
            JSONObject data = json.getJSONObject("JSON OBJECT NAME");
    
            ////GET A STRING////
    
            String title = data.getString("");
    
            //Similarly you can get other types of data
            //Replace String to the desired data type like int or boolean etc.
    
            } catch (JSONException e1) {
                e1.printStackTrace();
    
            }
    
            //GETTINGS DATA FROM JSON ARRAY//
    
            try {
    
                JSONObject jsonObject = new JSONObject(result);
                JSONArray postalCodesItems = new JSONArray(
                        jsonObject.getString("postalCodes"));
    
                    JSONObject postalCodesItem = postalCodesItems
                            .getJSONObject(1);
    
            } catch (Exception e) {
                Log.d("ReadPlacesFeedTask", e.getLocalizedMessage());
            }
        }
    }
    

    一个简单的替代解决方案:

    • 将URL粘贴到json到csv转换器中

    • 在Excel或Open Office中打开CSV文件

    • 使用电子表格工具解析数据

      • 有一个构建器,它接受一个对象:

        这意味着您可以从URL创建一个读卡器,然后将其传递给Gson以使用流并进行反序列化

        只有相关代码的三行

        import java.io.InputStreamReader;
        导入java.net.URL;
        导入java.util.Map;
        导入com.google.gson.gson;
        公共类GsonFetchNetworkJson{
        公共静态void main(忽略字符串[])引发异常{
        URL=新URL(“https://httpbin.org/get?color=red&shape=oval");
        InputStreamReader=新的InputStreamReader(url.openStream());
        MyDto dto=new Gson().fromJson(reader,MyDto.class);
        //使用反序列化对象
        System.out.println(dto.Header);
        System.out.println(dto.args);
        System.out.println(dto.origin);
        System.out.println(dto.url);
        }
        私有类MyDto{
        地图标题;
        地图参数;
        弦源;
        字符串url;
        }
        }
        
        如果某个端点碰巧收到403错误代码,而该端点在其他情况下工作正常(例如,使用
        curl
        或其他客户端),那么可能的原因可能是该端点需要
        User-Agent
        头,默认情况下,Java URLConnection未对其进行设置。一个简单的修复方法是在文件顶部添加,例如,
        System.setProperty(“http.agent”、“Netscape 1.0”)

        我使用Java1.8 使用com.fasterxml.jackson.databind.ObjectMapper

        ObjectMapper mapper = new ObjectMapper();
        Integer      value = mapper.readValue(new URL("your url here"), Integer.class);
        

        Integer.class也可以是复杂类型。举个例子。

        例如,它将是这样的,或者从facebook图形中,“java”标记表示他不想使用javascript。@Salah Yahya:添加了GSON示例+如何下载URL这将损坏JSON并产生解析错误。完全不需要从URL的接收内容构建自己的字符串,GSON支持直接从BufferedReader读取。这个例子并不适用于所有情况。你可以使用泛型加载任意的JSON吗?需要更新。链接断开了,不清楚应该用什么来代替最后的“…”这是一个非常低质量的答案。我不认为使用Excel是解决这个问题的一个复杂的解决方案。升级json到csv转换器可能吗?我认为您必须在
        新URL(…)
        之后添加
        .openStream()
        。所以它必须是这样的:
        jsonobjectjo=(JSONObject)newjsontokener(IOUtils.toString)(newurl(“http://gdata.youtube.com/feeds/api/videos/SIFL9qfmu5U?alt=json).nextValue()@Selphiron,工作正常。非常感谢。如果json-args包含数组元素呢?@Sundar:对于数组,您将使用TypeToken: