简体   繁体   中英

Convert String array to json in android

I have a problem. I want to pass String array to javascript, but this is impossible, so I want to convert String array to json and send it to java script. How can I do that?

Just convert use JSONArray,

import java.util.Arrays;
import org.json.JSONArray;
String[] inputs = new String[] {"foo", "bar"};
JSONArray jsonArray = new JSONArray(Arrays.asList(inputs));

A popular solution for Android would be the use of GSON: https://code.google.com/p/google-gson/

The package provides simple toJson and fromJson methods on its main converter object, so you get there quite easily. Alternatives like Jackson often require some additional preparation of the converted objects.

Try something like

LinkedList list = new LinkedList();
For(String s : array) {
     list.add(s);
}

String jsonText =     JSONValue.toJSONString(list)

You could try using FlexJSON for Serialization/Deserialization of objects. It has a nice and easy tutorial accessible on the website and is flexible in its usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM