Search code examples
javajsonlistjson-simple

Convert List to JsonObject in Java using json simple


I have a list -

List<Item> items = new ArrayList<Item>;

which consists of items - [firstname , abc , lastname , pqr , id , 1 ]

I need to convert this list to JSONObject of below format in java using json simple lib -

{"firstname":"abc","lastname":"pqr","id":"1"}

How can I achieve this? I am just a beginner.Any help would be appreciated.Thankyou in advance.


Solution

  • Got the answer -

    First converted the List to Map and then to Json -

    public Map<String, String> test() {
    
        Map<String, String> result = items.stream().collect(Collectors.toMap(Item::getValue, Item::getType)); //Converts List items to Map
    
        System.out.println("Result  : " + result);
    
        JSONObject json = new JSONObject(result); //Converts MAP to JsonObject
    
        System.out.println("JSON : " + json); //prints {"firstname":"abc","lastname":"pqr","id":"1"}
        return result;
    }