Reputation: 10930
I've a List of values, which is
List<Test> myList;
public class Test {
String type;
String value;
}
When I debug the List Value looks like
Test(type=6140, value=2017)
Test(type=6144, value=2017)
I want to convert this into a string,
So I tried with like
List<Test> myList;
StringBuilder abc = new StringBuilder();
for(Object a: myList){
abc.append(String.valueOf(a));
}
But the result will be like
Test(type=6140, value=2017)Test(type=6144, value=2017)
But I want to convert the value as
[{"type":6140,"value":"2017"},{"type":6144,"value":"2017"}]
Upvotes: 0
Views: 79
Reputation: 1549
if you override the toString method in class Test then the output will be as per your expection.
@Override
public String toString() {
return "{" +
"type=" + type +
", value=" + value +
'}';
}
output:
[{"type":6140,"value":"2017"},{"type":6144,"value":"2017"}]
Upvotes: 0
Reputation: 890
Try using GSON After including the library this task could be as simple as Gson gson = new Gson(); String jsonString = gson.toJson(myList)
Upvotes: 2
Reputation: 1917
You could either overwrite the ToString() function in your class 'Test' or serialize the objects with JSON. JSON will give you an other but similar output than wanted. So overwriting the function ToString() will fit your needs more.
Upvotes: 2