简体   繁体   中英

Access intended values in JSON file using JAVA

This is the JSON file I am working with

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

I need to access the value in label and score . using 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 .

You might want to have a look at JacksonXml for json parsing. Right now the problem is that you're not using the JsonObject returned by parser.parse(...) . Instead you use the get method on objects you just created. 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.

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")); while creating the 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.

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

I prefer the FasterXML Jackson support to parse JSON into plain old Java objects (POJOs). 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.

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.

static final ObjectMapper mapper = new ObjectMapper();

This is the JSON deserialization method:

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 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.

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.

You can use getJSONObject() , getString() , getFloat() instead of get() , in this way you don't need to cast the result.

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. After modeling the json as a composition of POJOs, the parsing takes 1 line of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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