简体   繁体   English

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

[英]Access intended values in JSON file using JAVA

This is the JSON file I am working with 这是我正在使用的JSON文件

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

I need to access the value in label and score . 我需要访问labelscore的值。 using java. 使用Java。 How can I do that? 我怎样才能做到这一点?

Find below the code I am using right now: 在下面找到我现在正在使用的代码:

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();
     }

Why is it printing the value as null . 为什么将值打印为null

You might want to have a look at JacksonXml for json parsing. 您可能想看看JacksonXml用于json解析。 Right now the problem is that you're not using the JsonObject returned by parser.parse(...) . 现在的问题是您没有使用parser.parse(...)返回的JsonObject。 Instead you use the get method on objects you just created. 而是在刚创建的对象上使用get方法。 This of course means that you don't getthe valie you want to. 当然,这意味着您不会获得想要的价格。

Try to use following code ( JSONObject jsonObject = (JSONObject) object instead of JSONObject jsonObject = new JSONObject(); ), because you didn't use object at all, just create new empty JSONObject. 尝试使用以下代码( 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();
        }

You have to make use of object created in Object object = parser.parse(new FileReader("output_nlu_sentiment.json")); 你必须要使用的object中创建Object object = parser.parse(new FileReader("output_nlu_sentiment.json")); while creating the jsonObject 在创建jsonObject

For that you can look at the code below: 为此,您可以查看下面的代码:

        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");

You will get the positive printed on console. 您将在控制台上得到positive印刷。

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

I prefer the FasterXML Jackson support to parse JSON into plain old Java objects (POJOs). 我更喜欢FasterXML Jackson支持将JSON解析为普通的旧Java对象(PO​​JO)。 These POJOs are often called Data Transfer Objects (DTOs) and give you a way to turn your JSON fields into properly typed members of the corresponding DTO. 这些POJO通常称为数据传输对象(DTO),为您提供一种将JSON字段转换为相应DTO的正确类型化成员的方法。

Here is an example method to do that. 这是执行此操作的示例方法。 The ObjectMapper(s) are generally maintained as statics somewhere else because FasterXML's implementation caches information to improve efficiency of object mapping operations. 由于FasterXML的实现会缓存信息以提高对象映射操作的效率,因此ObjectMapper通常在其他地方保持为静态。

static final ObjectMapper mapper = new ObjectMapper();

This is the JSON deserialization method: 这是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;
}

Assuming I have a class called FooDTO, which has the appropriate Jackson annotations/getters/setters (note you must always provide a default empty public constructor), you can do this: 假设我有一个名为FooDTO的类,该类具有适当的Jackson批注/获取器/设置器(请注意,您必须始终提供默认的空公共构造函数),您可以执行以下操作:

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

The deserialization throws a few different exceptions (all of which have IOException as their parent class) that you will need to handle or throw back to the caller. 反序列化引发了一些不同的异常(所有这些异常均具有IOException作为其父类),您需要处理这些异常或将其抛出给调用者。

Here besides of the correction alreay addressed in comments and other answers, I include some other changes you can benefit of: 除了在注释和其他答案中解决的修正问题外,这里还包括您可以从中受益的其他一些更改:

It is not necessary to initialize the JSONObjects with a new instance that is going to be ovewritten in the next line. 不必使用将在下一行中重写的新实例来初始化JSONObjects。

You can use getJSONObject() , getString() , getFloat() instead of get() , in this way you don't need to cast the result. 您可以使用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();
       }
}

Also for this kind of objects, where the attribute names could act as object properties, I suggest you take a look at Gson library. 同样对于这类对象,属性名称可以用作对象属性,我建议您看一下Gson库。 After modeling the json as a composition of POJOs, the parsing takes 1 line of code. 在将json建模为POJO的组合之后,解析需要1行代码。

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

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