-1

I hope I am not asking a question which don't make any sense. Lets say I have JSON data like below. In JAVA we can access data by using get method (ex. jsonObj.get("field1")). When it comes to JavaScript we can access data directly using field name (ex. jsonObj.field1). So my question is, is there anyway in JAVA (or any 3rd party class) which allow me to access JSON data directly using field name?

   { 
      "field1" : "value1",
      "field2" : "value2"
    }
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
krishna_5c3
  • 509
  • 6
  • 14

1 Answers1

0

You can use GSON library and create object model class, then individual properties can be access using getter's

    File file = new File("XXXXXX.json");
    String JSONString = Files.toString(file, Charsets.UTF_8);
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();
    ModelClass modelClass = gson.fromJson(JSONString, modelClass.class);
    System.out.print("modelClass field -->" + modelClass.getFIELDNAME());

Hope this helps!

Note: field name and type used in model class should be same as field name and type from JSON.

  • Thanks @NayanSuchak. I am aware of that but, I want to access it like a static variable ex. `obj.FIELDNAME` not by any methods. – krishna_5c3 Nov 22 '17 at 16:31