Dorine
Dorine

Reputation: 23

Getting value from json item in java

I have a json file, for example:

{
  "A":"-0.4",
  "B":"-0.2",
  "C":"-0.2",
  "D":"X",
  "E":"0.2",
  "F":"0.2",
  "J":"0.3"

}

I want return each element of a list json when I call it via my function. I did a function to do this:

public JSONObject my_function() {
JSONParser parser = new JSONParser();

    List<JSONObject> records = new ArrayList<JSONObject>();
    try (FileReader reader = new FileReader("File.json")) {

        //Read JSON file
        Object obj = parser.parse(reader);
        JSONObject docs = (JSONObject) obj;
        LOGGER.info("read elements" + docs); // it display all a list of a json file like this: {"A":"-0.4","B":"-0.2","C":"-0.2","D":"X","E":"0.2","F":"0.2","J":"0.3"}


        for (int i = 0; i < docs.size(); i++) {
            records.add((JSONObject) docs.get(i));
            System.out.println((records)); // it return null 

        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    LOGGER.info("The first element of a list is:" +records.get(0)); // return null
    return records.get(0);

How can I change my function to return the value of each element in a json file. For example, when I call my_function:

my_function.get("A") should display -0.4

Thank you

Upvotes: 1

Views: 82

Answers (2)

majurageerthan
majurageerthan

Reputation: 2319

First you need a Class for mapping

public class Json {

private String a;
private String b;
private String c;
private String d;
private String e;
private String f;
private String j;

//getters and setters

}

Then in your working class

ObjectMapper mapper = new ObjectMapper();

//JSON from file to Object
Json jsn = mapper.readValue(new File("File.json"), Json.class);

then you can use that object in a usual way...

here is the dependency I used

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>

Reference

Upvotes: 3

Dred
Dred

Reputation: 1118

In Java you can use only class`s methods, as I know. If you want to get your second element by its first, you should in your class create 2 methods like

class Main {
Map<String, String> records = new HashMap<>();

public JSONObject my_function() {
// your realization where you should insert your pairs into Map.
}

public String get(String firstElement){
return map.getValue(firstElement);
}

}


class someOtherClass {
Main main = new Main();
main .my_function();
main .get("A");

}

Upvotes: 0

Related Questions