【问题标题】:Read the JSON file in the Jersey sources folder读取 Jersey 源文件夹中的 JSON 文件
【发布时间】:2015-09-01 17:24:45
【问题描述】:

我有 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);
}

}

【问题讨论】:

    标签: java json jersey jackson


    【解决方案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();
            }
    

    【讨论】:

    • 感谢您的回答。不需要ObjectMapper吗?
    • 你想做什么?您是要从文件中读取数据还是要将文件中的 json 映射到 Java 对象?
    • 我在此路径src/main/sources/routes.txt 中有像上面简单的 JSON 一样的 JSONArray .txt 文件,我想读取该文件以从 json 文件中获取时间或任何其他信息。
    • 我收到这些错误File cannot be resolved to a type - FileInputStream cannot be resolved to a type
    • 我已经用这个链接jsonschema2pojo.org创建了类,我也为这个JSON简单的4个类创建了链接。
    【解决方案2】:

    需要考虑的事情很少。

    • JSON 的反序列化和格式。 目前您的 JSON 是一个 JSON 数组。除非该类是某种类型的集合,比如List 的子类,否则该类将映射到 JSON 对象。因此,您可以从 JSON 中删除 [ ],或者反序列化为 List&lt;Root&gt;。例如

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

      当然,如果您删除了[ ],那么您可以反序列化为Root 而不是List&lt;Root&gt;。但也许您希望数组中有更多 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);
                }
            }
        }
    }
    

    【讨论】:

    • Stops 是一个arra 时,你能告诉我如何访问到达时间吗?因为它是一个数组,我忘了在上面的简单中添加方括号。
    • 把类名改成Stop,这样才有意义,把Info里的文件改成List&lt;Stop&gt; stops
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-17
    • 2017-05-18
    • 2023-03-24
    相关资源
    最近更新 更多