Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting json from a file to a java object

Tags:

java

json

I am trying to convert json from a text file into a java object.

I have tried both the jackson library, I put in the dependency and what not. My json file has both camel case and underscores, and that is causing an error when running my program. Here is the code that I used for when relating to the gson librar and it does not do anything, the output is the same with or without the code that I placed.

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

Now I also tried the jackson library. Here is the code i used

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

I am not sure what to do,

like image 464
Jack Avatar asked Dec 02 '22 21:12

Jack


2 Answers

This simple example works like a charm:
DTOs

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

Jackson

  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!"
   }
}
like image 92
Ilya Avatar answered Dec 15 '22 18:12

Ilya


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);
}
like image 24
Vinit Jordan Avatar answered Dec 15 '22 19:12

Vinit Jordan