简体   繁体   English

在 Java 中构建 JSONObject 而不抛出异常

[英]Building a JSONObject in Java without throwing an exception

Is there a way in Java to build a JSONObject without having to deal with an exception? Java 中有没有一种方法可以构建 JSONObject 而不必处理异常? Currently I'm using the default constructor, which however forces me to put try/catch blocks in the code.目前我正在使用默认构造函数,但这迫使我在代码中放置 try/catch 块。 Since in the rest of the code I'm using the "opt" version of get, checking if the return value is null, is there a way to build the object in the same way?由于在其余代码中我使用的是 get 的“opt”版本,检查返回值是否为空,有没有办法以相同的方式构建对象? (that is, some kind of constructor that returns null if it can't build the json from a string). (也就是说,某种构造函数如果无法从字符串构建 json 则返回 null)。

Example:例子:

         try {
               JSONObject temp = new JSONObject(someString);
         } catch (JSONException e) {
               e.printStackTrace();
         }

What I would like to do:我想做什么:

JSONObject temp = ??????(someString);
if(temp != null) {...}

You need to create the method manually, as any parser will most probably throw one or the other Exception in case of any discrepancy.Try something like this:-您需要手动创建该方法,因为任何解析器很可能会在出现任何差异时抛出一个或另一个Exception 。尝试如下操作:-

 public JSONObject verifyJSON(String inputString){
        JSONObject temp;
        try {
            temp = new JSONObject(inputString);
      } catch (JSONException e) {
          temp = null;
            e.printStackTrace();

      }
        return temp;
    }

Then you can do :-然后你可以这样做:-

JSONObject temp = verifyJSON(someString);
if(temp != null) {...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM