有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

迭代JSON字段及其子字段,并将这些键值与其他类的java对象进行比较

我有一个类似json的

 {
"debug": "on",
"window": {
    "title": "Sample Konfabulator Widget",
    "name": "main_window",
    "width": 500,
    "height": 500
},
"image": { 
    "src": "Images/Sun.png",
    "name": "sun1",
    "hOffset": 250,
    "vOffset": 250,
    "alignment": "center"
},
"text": {
    "data": "Click Here",
    "size": 36,
    "style": "bold",
    "name": "text1",
    "hOffset": 250,
    "vOffset": 100,
    "alignment": "center",
    "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
   }

我想将json的键值与我的java类dto的键值进行比较。每个对象列表都有一个单独的类,比如window,image。所有对象的定义都存在于单独的java类示例中,如下所示

   public class Address {
private String debug;
private Window List<window>;
private Image List<text>;
----getter and setter ---
   }

我已经为json遍历编写了以下代码片段,但我不知道如何将json映射器的键值与对象进行比较。应该按系统顺序进行比较,例如在检查窗口对象之后,我们必须检查标题、名称

    public static void main(String[] args) throws  Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    consignment consignment = new consignment();
    consignment.function();

    Path path = Paths.get("src/main/resources/consignmentEvent.json");
    String contents = null;
    try {
        contents = Files.readString(path, StandardCharsets.ISO_8859_1);
    } catch (IOException ex) {
        // Handle exception
    }
   JSONObject jsonObject = new JSONObject(contents.trim());
  printJsonObject(jsonObject);
  }

public static void printJsonObject(JSONObject jsonObj) {
    for (Object key : jsonObj.keySet()) {
        //based on you key types
        String keyStr = (String)key;
        Object keyvalue = jsonObj.get(keyStr);
        //Print key and value
        System.out.println("key: "+ keyStr );
        //for nested objects iteration if required
        int flag=0;
        if (keyvalue instanceof JSONObject)
            printJsonObject((JSONObject)keyvalue);
    }
}

共 (0) 个答案