我有Jersey项目glassfish 2.18
,我正在尝试使用Jackson 2.x在此文件夹scr-main-sources中读取JSON文件routes.txt
。如何获取文本文档文件的InputStream以从中获取数据?
我感谢任何帮助
代码:
FileReader fileReader = new FileReader("src/main/sources/routes.txt");
ObjectMapper mapper = new ObjectMapper();
Root readValue = mapper.readValue(fileReader, Root.class);
JSON简单:
[{
"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"
}
}]
根类:
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);
}
}
答案 0 :(得分:2)
很少有事情需要考虑。
反序列化和格式化JSON。目前您的JSON是一个JSON数组。除非类是某种类型的集合,比如List
的子类,否则该类将映射到JSON对象。因此,您可以从JSON中删除[ ]
,也可以反序列化为List<Root>
。例如
List<Root> roots = mapper.readValue(is, TypeFactory.defaultInstance()
.constructCollectionType(List.class, Root.class));
当然,如果您移除[ ]
,则可以反序列化为Root
而不是List<Root>
。但也许你期望在数组中有更多的JSON对象(谁知道)。
与您的Root
类相关的主JSON对象的格式。 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;
}
}
}
访问文件。应该从类路径而不是文件系统上的文件中读取该文件。为此,您可以使用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 :(得分: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
,那么您可以选择:
之前的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();
}