将json从文件转换为java对象

时间:2013-09-05 13:52:26

标签: java json

我正在尝试将json从文本文件转换为java对象。

我已经尝试了两个jackson库,我放入了依赖,什么不是。我的json文件有驼峰大小写和下划线,这在运行我的程序时会导致错误。这是我在与gson librar相关时使用的代码,它没有做任何事情,输出是相同的,有或没有我放置的代码。

  java.net.URL url = this.getClass().getResource("/test.json");
          File jsonFile = new File(url.getFile());
          System.out.println("Full path of file: " + jsonFile);
try 
      {

         BufferedReader br = new BufferedReader(new FileReader("/test.json"));

         // convert the json string back to object
         DataObject obj = gson.fromJson(br, DataObject.class);

         System.out.println(obj);

      } catch (IOException e) 
      {
         e.printStackTrace();
      }

现在我也尝试了杰克逊图书馆。这是我使用的代码

java.net.URL url = this.getClass().getResource("/test.json");
      File jsonFile = new File(url.getFile());
      System.out.println("Full path of file: " + jsonFile);

ObjectMapper mapper = new ObjectMapper();
       mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
       InputStream is = Test_Project.class.getResourceAsStream("/test.json");
       SampleDto testObj = mapper.readValue(is, SampleDto.class);
       System.out.println(testObj.getCreatedByUrl());

我不知道该怎么做,

2 个答案:

答案 0 :(得分:10)

这个简单的例子就像一个魅力: DTO

public class SampleDTO 
{
   private String name;
   private InnerDTO inner;
   // getters/setters
}

public class InnerDTO 
{
   private int number;
   private String str; 
   // getters/setters  
}  

Gson

  BufferedReader br = new BufferedReader(new FileReader("/tmp/test.json"));
  SampleDTO sample = new Gson().fromJson(br, SampleDTO.class);  

杰克逊

  InputStream inJson = SampleDTO.class.getResourceAsStream("/test.json");
  SampleDTO sample = new ObjectMapper().readValue(inJson, SampleDTO.class);

JSON test.json

{
   "name" : "Mike",
   "inner": {
      "number" : 5,
      "str" : "Simple!"
   }
}

答案 1 :(得分:0)

public static void main(String args[]){

   ObjectMapper mapper = new ObjectMapper();

  /**
    * Read object from file
    */
   Person person = mapper.readValue(new File("/home/document/person.json"), Person.class);
   System.out.println(person);
}