【问题标题】:Parse local JSON file with RestTemplate使用 RestTemplate 解析本地 JSON 文件
【发布时间】:2012-07-31 20:06:09
【问题描述】:

我想解析一个本地 JSON 文件并使用 RestTemplate 将其编组为模型,但不知道这是否可行。

我正在尝试在使用 RestTemplate 与服务器同步的 Android 应用上预填充数据库。我想,与其自己解析本地 JSON,不如使用 RestTemplate?它专门用于将 JSON 解析为模型。

但是...我无法从文档中判断是否有任何方法可以做到这一点。有 MappingJacksonHttpMessageConverter 类似乎将服务器的 http 响应转换为模型......但是有没有办法破解它来处理本地文件?我试过了,但一直越陷越深,没有运气。

【问题讨论】:

    标签: java android spring resttemplate


    【解决方案1】:

    想通了。您可以直接使用 Jackson,而不是使用 RestTemplate。没有理由 RestTemplate 需要参与其中。很简单。

    try {
        ObjectMapper mapper = new ObjectMapper();
    
        InputStream jsonFileStream = context.getAssets().open("categories.json");
    
        Category[] categories = (Category[]) mapper.readValue(jsonFileStream, Category[].class);
    
        Log.d(tag, "Found "  + String.valueOf(categories.length) + " categories!!");
    } catch (Exception e){
        Log.e(tag, "Exception", e);
    }
    

    【讨论】:

      【解决方案2】:

      是的,我认为这是可能的(使用 MappingJacksonHttpMessageConverter)。

      MappingJacksonHttpMessageConverter 有方法 read() 有两个参数:ClassHttpInputMessage

      MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
      YourClazz obj = (YourClazz) converter.read(YourClazz.class, new MyHttpInputMessage(myJsonString));
      

      使用此方法,您可以从单个 json 消息中读取单个对象,但 YourClazz 可以是一些集合。

      接下来,您必须创建自己的 HttpInputMessage 实现,在此示例中,它期望 json 作为字符串,但您可能可以将流传递给您的 json 文件。

      public class MyHttpInputMessage implements HttpInputMessage {
      
          private String jsonString;
      
          public MyHttpInputMessage(String jsonString) {
              this.jsonString = jsonString;
          }
      
          public HttpHeaders getHeaders() {
              // no headers needed
              return null;
          }
      
          public InputStream getBody() throws IOException {
              InputStream is = new ByteArrayInputStream(
                      jsonString.getBytes("UTF-8"));
              return is;
          }
      
      }
      

      附言。 You can publish your app with database

      【讨论】:

      • 感谢您的好回答。我尝试了这种方法,但不断收到异常“无法反序列化...的实例”。我找到了一个更好的解决方案,我将分享。
      猜你喜欢
      • 1970-01-01
      • 2016-09-02
      • 2016-06-19
      • 2015-01-11
      • 2013-07-30
      • 2018-12-20
      • 2011-12-05
      • 2019-04-23
      • 2012-05-10
      相关资源
      最近更新 更多