I have a Sring s (JSON array) [{"Phonetype":"Pre","Phone":"918282311"},{"Phonetype":"pre","Phone":"918333222"}]
and now i want to convert this string to JSON array of the JSON objects.
in my code i only can create a JSONrray of objects...
@Override
public ArrayList<TelephoneNumber> convertToAttribute(String s) {
ArrayList<TelephoneNumber> list = new ArrayList<TelephoneNumber>();
JSONParser parser = new JSONParser();
JSONArray arr = null;
try {
arr = (JSONArray) parser.parse(s);
}
catch (ParseException e) {
e.printStackTrace();
}
for (JSONObject jo: arr)
{
System.out.println("obj " +jo.get("Phone");
}
//create a list
return list;
}
how create a JsonArray of JsonObjects?
I'd recommend taking a look at Gson . It is a series of Java classes written by The Google Overlords that handles serializing and deserializing JSON from and to Java classes.
So, making a few assumptions about what your TelephoneNumber
class looks like, you should be able to do this:
Type listType = new TypeToken<ArrayList<TelephoneNumber>>() {
}.getType();
ArrayList<TelephoneNumber> yourList = new Gson().fromJson(s, listType);
Then return yourList
....
Consider using Gson to parse json values and use FieldNamingPolicy
on a GsonBuilder
to get a Gson
object that handles upper camel case names correctly:
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
Type listType = new TypeToken<ArrayList<TelephoneNumber>>() {}.getType();
List<TelephoneNumber> numbers = gson.fromJson(jsonArray, listType);
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.