簡體   English   中英

將 POJO 轉換為 Map<string, string> ?</string,>

[英]Convert POJO to Map<String, String>?

我正在尋找將整個 pojo 轉換為Map<String,String>的實用程序。 我可以看到所有示例,其中 pojo 被轉換為Map<String,Object>

但我正在專門尋找Map<String,String>

在這里,重要的是要了解 POJO 的關鍵和價值。 您可以覆蓋 POJO 的 toString 並將其用作值。

public class Main {

    public static void main(String[] args) {

        Map<String, String> result = new HashMap<>();
        result.put("key1", new POJO("Done").toString());
        result.put("key2", new POJO("Clarke").toString());

    }
}


public class POJO {
    private String name;

    public POJO(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

如果使用字段名作為鍵,可以使用反射。 請注意,如果將 POJO 中的字段修飾符更改為私有,則需要稍微更改代碼。 閱讀有關反射的信息。

public class Main {

public static void main(String[] args) throws IllegalAccessException {

    Map<String, String> result = new HashMap<>();

    POJO pojo = new POJO("okGoogle", 12345);
    Class classPOJO = pojo.getClass();

    Field [] allFields = classPOJO.getFields();
    for(Field field : allFields){
        String key = field.getName();
        String value = null;
        if( field.get(pojo) != null){
            value = field.get(pojo).toString();
        }
            result.put(key, value);
        }

        System.out.println(result.get("name"));
        System.out.println(result.get("id"));

    }
}

POJO model

public class POJO {
    public String name;
    public int id;

    public POJO(String name, int id) {
        this.name = name;
        this.id = id;
    }

}

我正在將每個 pojo 轉換為 map,然后創建一個 map 來存儲代表 pojo class 的所有地圖。

public class Main {

    public static void main(String[] args) {

    Person person = new Person();
           person.setName("Abhishek");
           person.setAge("30");

    Person person1 = new Person();
           person1.setName("Abhi");
           person1.setAge("28");

    Map<String,  Map<String, String>> resultMap = new HashMap<>();
    Map<String, String> result = new HashMap<>();
    result.put("name", person.getName());
    result.put("age", person.getAge());
    resultMap.put("object1", result);

    result = new HashMap<>();
    result.put("name", person1.getName());
    result.put("age", person1.getAge());
        resultMap.put("object2", result);
    }
}

public class Person {
    private String name;

    private String age

   //setters and getters

}

暫無
暫無

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

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