繁体   English   中英

使用JAVA访问JSON文件中的预期值

[英]Access intended values in JSON file using JAVA

这是我正在使用的JSON文件

{"sentiment": 
    {"document": 
         {
             "label": "positive",
             "score": 0.53777
         }
    }
}

我需要访问labelscore的值。 使用Java。 我怎样才能做到这一点?

在下面找到我现在正在使用的代码:

JSONParser parser = new JSONParser();
     try
     {
           Object object = parser
                   .parse(new FileReader("output_nlu_sentiment.json"));

           //convert Object to JSONObject
           JSONObject jsonObject = new JSONObject();
           JSONObject sentimentobject= new JSONObject();
           JSONObject documentobject = new JSONObject();

           sentimentobject= (JSONObject) jsonObject.get("sentiment");
           documentobject= (JSONObject) sentimentobject.get("document");

           String label = (String) documentobject.get("label");
           //float score = (float) jsonObject.get("score");
           System.out.println(label);


           String test = (String) sentimentobject.get("label");
           System.out.println(test);
        } catch(FileNotFoundException fe)
        {
           fe.printStackTrace();
        }
     catch(Exception e)
     {
        e.printStackTrace();
     }

为什么将值打印为null

您可能想看看JacksonXml用于json解析。 现在的问题是您没有使用parser.parse(...)返回的JsonObject。 而是在刚创建的对象上使用get方法。 当然,这意味着您不会获得想要的价格。

尝试使用以下代码( JSONObject jsonObject = (JSONObject) object而不是JSONObject jsonObject = new JSONObject(); ),因为您根本没有使用对象,只需创建新的空JSONObject。

JSONParser parser = new JSONParser();
     try
        {
            Object object = parser
                    .parse(new FileReader("output_nlu_sentiment.json"));

            //convert Object to JSONObject
            JSONObject jsonObject = (JSONObject) object;

            JSONObject sentimentobject = (JSONObject) jsonObject.get("sentiment");
            JSONObject documentobject= (JSONObject) sentimentobject.get("document");

            String label = (String) documentobject.get("label");               
            System.out.println(label);   

            float score = (float) documentobject.get("score");
            System.out.println(score );
        }catch(FileNotFoundException fe)
        {
            fe.printStackTrace();
        }
     catch(Exception e)
        {
            e.printStackTrace();
        }

你必须要使用的object中创建Object object = parser.parse(new FileReader("output_nlu_sentiment.json")); 在创建jsonObject

为此,您可以查看下面的代码:

        Object object = parser
                .parse(new FileReader("file2.json"));

        //convert Object to JSONObject
        JSONObject jsonObject = (JSONObject) object;
        JSONObject sentimentobject= new JSONObject();
        JSONObject documentobject = new JSONObject();

        sentimentobject= (JSONObject) jsonObject.get("sentiment");
        documentobject= (JSONObject) sentimentobject.get("document");

        String label = (String) documentobject.get("label");
        //float score = (float) jsonObject.get("score");
        System.out.println(label);


        String test = (String) sentimentobject.get("label");

您将在控制台上得到positive印刷。

您应该在para'sentimentobject'中看到内容,强制转换为JSONObject类无法获取所需的值。

我更喜欢FasterXML Jackson支持将JSON解析为普通的旧Java对象(PO​​JO)。 这些POJO通常称为数据传输对象(DTO),为您提供一种将JSON字段转换为相应DTO的正确类型化成员的方法。

这是执行此操作的示例方法。 由于FasterXML的实现会缓存信息以提高对象映射操作的效率,因此ObjectMapper通常在其他地方保持为静态。

static final ObjectMapper mapper = new ObjectMapper();

这是JSON反序列化方法:

public static <T> T deserializeJSON(
        final ObjectMapper mapper, final InputStream json,
        final Class<T> clazz)
        throws JsonParseException, UnrecognizedPropertyException,
                JsonMappingException, IOException
{
    final String sourceMethod = "deserializeJSON";
    logger.entering(sourceClass, sourceMethod);

    /*
     * Use Jackson support to map the JSON into a POJO for us to process.
     */
    T pojoClazz;

    pojoClazz = mapper.readValue(json, clazz);

    logger.exiting(sourceClass, sourceMethod);
    return pojoClazz;
}

假设我有一个名为FooDTO的类,该类具有适当的Jackson批注/获取器/设置器(请注意,您必须始终提供默认的空公共构造函数),您可以执行以下操作:

FooDTO foo = deserializeJSON(mapper, inputstream, FooDTO.class);

反序列化引发了一些不同的异常(所有这些异常均具有IOException作为其父类),您需要处理这些异常或将其抛出给调用者。

除了在注释和其他答案中解决的修正问题外,这里还包括您可以从中受益的其他一些更改:

不必使用将在下一行中重写的新实例来初始化JSONObjects。

您可以使用getJSONObject()getString()getFloat()而不是get() ,通过这种方式,您无需转换结果。

public void parseJson() {
    JSONParser parser = new JSONParser();
    try
       {
           JSONObject jsonObject = new JSONParser().parse(new FileReader("output_nlu_sentiment.json"));
           JSONObject sentimentobject= null;
           JSONObject documentobject = null;

          sentimentobject=  jsonObject.getJSONObject("sentiment");
          documentobject=   sentimentobject.getJSONObject("document");

          String label =  documentobject.getString("label");
           float score =  documentobject.getFloat("score");
           String output = String.format("Label: %s Score: %f", label, score);
           System.out.println(output);

       }catch(FileNotFoundException fe){
           fe.printStackTrace();
       }catch(Exception e){
           e.printStackTrace();
       }
}

同样对于这类对象,属性名称可以用作对象属性,我建议您看一下Gson库。 在将json建模为POJO的组合之后,解析需要1行代码。

暂无
暂无

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

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