Spandana
Spandana

Reputation: 141

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.

Upvotes: 0

Views: 15476

Answers (1)

Isha
Isha

Reputation: 62

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;
}

Upvotes: 4

Related Questions