Query a JSONObject in java

后端 未结 6 1719
鱼传尺愫
鱼传尺愫 2020-11-27 06:12

I was wondering if somewhere out there exists a java library able to query a JSONObject. In more depth I\'m looking for something like:



        
6条回答
  •  我在风中等你
    2020-11-27 06:59

    I think no way.

    Consider a java class

    class Student {
        Subject subject = new Subject();
    }
    
    class Subject {
        String name;
    }
    

    Here if we want to access subject name then

    Student stud = new Student();
    stud.subject.name; 
    

    We cant access name directly, if so then we will not get correct subject name. Like here:

    jsonObject.getAsJsonObject("data")
              .getAsJsonObject()
              .get("data2")
              .getAsJsonObject("value")
              .getAsString();
    

    If you want to use same like java object then use

    ClassName classObject = new Gson().fromJson(JsonString, ClassName.class);
    

    ClassName must have all fields to match jsonstring. If you have a jsonobject inside a jsonobject then you have to create separate class like I'm doing in Student and Subject class.

提交回复
热议问题