0

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.

7
  • is the List data constant like you mentioned, first element is name, second element is its value, like wise on and on ??? Commented Jan 20, 2017 at 10:17
  • Also, Can you please add the Code of Item Class ? Commented Jan 20, 2017 at 10:19
  • Is Item a String ? or some other kind of class ? Commented Jan 20, 2017 at 10:20
  • No,not constant.. I am getting the values in List from Bean Item by inputting values in TextFields. Commented Jan 20, 2017 at 10:22
  • Can you Put your Item Class structure? because you need to convert list to map and then to json.So It required to show how your Item class is exactly look like Commented Jan 20, 2017 at 10:25

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.