簡體   English   中英

將json從文件轉換為java對象

[英]Converting json from a file to a java object

我正在嘗試將 json 從文本文件轉換為 java 對象。

我已經嘗試了 jackson 庫,我放入了依賴項,什么沒有。 我的 json 文件有駝峰式大小寫和下划線,這在運行我的程序時導致錯誤。 這是我在與 gson 庫相關時使用的代碼,它沒有做任何事情,無論有沒有我放置的代碼,輸出都是相同的。

  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();
      }

現在我也嘗試了 jackson 庫。 這是我使用的代碼

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());

我不知道該怎么做,

這個簡單的例子就像一個魅力:
DTO

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

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

格森

  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!"
   }
}
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);
}

在文件中獲取 json 數組或僅獲取 json 的常用方法是

InputStream inputStream= Employee.class.getResourceAsStream("/file.json");
CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(List.class, Employee.class);

List<Employee> lstEmployees = mapper.readValue(inputStream, collectionType);

file.json 需要放在資源文件夾中。 如果您的文件只有一個沒有 json 數組方括號 [] 的 json 塊,您可以跳過 CollectionType

InputStream inputStream= Employee.class.getResourceAsStream("/file.json");
Employee employee = mapper.readValue(inputStream, Employee.class);

另請參閱此處了解我從哪里得出的原始問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM