How to check the content of readValue

1

You'll see I'm messing around with the NBA API and I have this json in particular

link

Then I have a Parser class

public class Parser {

    private Map<String, Object> otherProperties = new HashMap<String, Object>();

    @JsonAnySetter
    public void set(String name, Object value) {
            otherProperties.put(name, value);

    }

    @Override
    public String toString() {
        return "Parser{" +
                ", otherProperties=" + otherProperties +
                '}';
    }
}

Followed by a main that works properly for me and shows the contents of that json file on screen.

   public static void main(String args[]) throws JsonParseException,
            JsonMappingException, IOException {

        ObjectMapper mapper = new ObjectMapper();
        Parser car = mapper.readValue(new File("full_schedule.json"), Parser.class);

        System.out.println(car);

    }

I want to know if there is a way to check the value returned by the json, not show the entire string itself, if not know if there is any way to iterate this property.

    
asked by jc1992 26.09.2017 в 17:15
source

1 answer

0

I do not know exactly what is not clear to you, but I will try to explain what I see and what options you have:

You have created a Parser object that contains an instance of Map, saving all the JSON.

First let's modify your code a bit:

public class Parser {

    private Map<String, Object> otherProperties = new HashMap<String, Object>();

    @JsonAnySetter
    public void set(String name, Object value) {
        otherProperties.put(name, value);

    }
    public Object get(String key) {
        return this.otherProperties.get(key);
    }

    @Override
    public String toString() {
        return "Parser{" + ", otherProperties=" + otherProperties + '}';
    }
}

Now you can "navigate" through the JSON values. Since the element lscd was a list of elements, in Java it becomes a List, and in the first position we will have an object (again "mapped" to a Map whose key is "mscd"). You can get the names of the months like this:

public static void main(String args[]) throws JsonParseException, IOException {

        ObjectMapper mapper = new ObjectMapper();
        InputStream data = Parser.class.getResourceAsStream("/file.json");
        Parser car = mapper.readValue(data, Parser.class);
        List<Map<String,Object>> lscd=(List<Map<String,Object>>) car.get("lscd");
        for (Map<String,Object> item: lscd) {
            Map<String,Object> month=(Map<String, Object>) item.get("mscd");
            System.out.println(month.get("mon"));
        }
    }

It's pretty tricky, but in general the rule is that if in the JSON the value starts with:

  • Key { : it's a Map
  • Bracket [ : It's a List
  • Quotes " : It's a String
  • A number: It's a number, better proof to use double or BigDecimal if you think it can have decimals.
answered by 26.09.2017 в 18:18