List <String> to Json String

How can I convert a list to a Json string?

I managed to do it the other way around, but not in this way.

I also don't know how I can specify the key names then.

+3


source to share


2 answers


You can use Gson Library .

List<String> list;
String json = new Gson().toJson(list);

      



Edited

Just to get the complete answer here: The problem is you are converting json String to List<String>

. Thus, you lose the key value connection. The correct one is to convert the json string to HashMap<>

.

+4


source


Your real problem seems to be that when you originally turned the JSON string into List

, you threw away the keys. And it comes as no surprise that List is not a natural representation of a JSON object (i.e. Things with key-value pairs). You should probably have presented it as Map

.



But in any case, if you threw away the keys, you have a problem. You need to either change the data structure, or not discard the keys, or restore the JSON by specifying which keys should be based on (for example) their position in the list. (The latter can be a little quirky, because the order of the name / value pairs in the original JSON doesn't have to mean anything ... and could be "random" or "implementation dependent".

+1


source







All Articles