Read the JSON file in the Jersey sources folder

I have a jersey project glassfish 2.18and am trying to read the JSON file routes.txtin this folder with the main sources using Jackson 2.x. How can I get an InputStream of a text document file to get data from it?

I appreciate any help

The code:

    FileReader fileReader = new FileReader("src/main/sources/routes.txt");
    ObjectMapper mapper = new ObjectMapper();
    Root readValue = mapper.readValue(fileReader, Root.class);

JSON simple:

[{
   "route": 1,
   "info": {
              "stops": [{
                          "arrival_time": {"mon-fri": ["04:24","05:10","05:40"],
                                       "sat": ["05:34","05:55","06:15"],
                                       "son": ["07:00","08:00","05:40"]

                                       },
                          "stops_name": "Tension Way"
                        }],
              "direction": "Surrey Quays"
           }
}]

Root class:

package org.busTracker.serverSide.json;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"route",
"info"
})
public class Root {

@JsonProperty("route")
private Integer route;
@JsonProperty("info")
private Info info;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

/**
* 
* @return
* The route
*/
@JsonProperty("route")
public Integer getRoute() {
return route;
}

/**
* 
* @param route
* The route
*/
@JsonProperty("route")
public void setRoute(Integer route) {
this.route = route;
}

/**
* 
* @return
* The info
*/
@JsonProperty("info")
public Info getInfo() {
return info;
}

/**
* 
* @param info
* The info
*/
@JsonProperty("info")
public void setInfo(Info info) {
this.info = info;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}
+4
source share
2 answers

Something to think about.

  • Deserializing and JSON format. Your JSON is currently a JSON array. If the class is not a collection type, say a subclass List, the class will display a JSON object. That way you can either remove [ ]from JSON or deserialize to List<Root>. for instance

    List<Root> roots = mapper.readValue(is, TypeFactory.defaultInstance()
                .constructCollectionType(List.class, Root.class));
    

    , [ ], Root List<Root>. , , , JSON ( ).

  • JSON Root. , JSON . , ( ):

    public class Root {
    
        public int route;
        public Info info;
    
        public static class Info {
    
            public String direction;
            public Stops stops;
    
            public static class Stops {
                @JsonProperty("arrival_time")
                public Map<String, String[]> arrivalTime = new HashMap<>();
                @JsonProperty("stops_name")
                public String stopsName;
            }
        }
    }
    
  • . classpath . Class.getResourceAsStream(), InputStream. , src/main/resources ( Maven), , ,

    InputStream is = YourClass.class.getResourceAsStream("/file.json")
    

public class Main {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        InputStream is = Main.class.getResourceAsStream("/file.json");

        List<Root> roots = mapper.readValue(is, TypeFactory.defaultInstance()
                .constructCollectionType(List.class, Root.class));
        Root root = roots.get(0);

        System.out.println("route: " + root.route);
        Map<String, String[]> arrivalTimes = root.info.stops.arrivalTime;
        for (Map.Entry<String, String[]> entry: arrivalTimes.entrySet()) {
            System.out.println(entry.getKey());
            for (String time: entry.getValue()) {
                System.out.println(time);
            }
        }
    }
}
+1

JAVA:

    ObjectMapper mapper = new ObjectMapper();
    Root readValue = mapper.readValue( new FileReader("src/main/sources/routes.txt"), Root.class);
    Info info = readValue.getInfo();
    System.out.println(info.toString()); //Remove from production code
    Stops stops = info.getStops();
    System.out.println(stops.toString()); //Remove from production code 

, :

:

BufferedReader br = new BufferedReader(fileReader);
String s;
while ((s = br.readLine()) != null) {
    System.out.println("value are " + s);
}

, File InputStream, :

Prior Java 1.7:

InputStream fis = null;
    try {
        fis = new FileInputStream(new File("src/main/sources/routes.txt"));

        System.out.println("Total file size to read (in bytes) : "
                + fis.available());

        int content;
        while ((content = fis.read()) != -1) {
            // convert to char and display it
            System.out.print((char) content);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

Java 1.7 :

try (InputStream fis = new FileInputStream(new File(
                "src/main/sources/routes.txt"))) {
            System.out.println("Total file size to read (in bytes) : "
                    + fis.available());
            int content;
            while ((content = fis.read()) != -1) {
                // convert to char and display it
                System.out.print((char) content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
0

All Articles