Reputation: 141
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
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