0

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?

vzamanillo
  • 9,905
  • 1
  • 36
  • 56
Gui Pinto
  • 57
  • 9

2 Answers2

0

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....

Tom Mac
  • 9,693
  • 3
  • 25
  • 35
  • Thanks @Tom Mac. But the fields appears Null. fist i print the list and give me [DN_Schema.TelephoneNumber@64616ca2, DN_Schema.TelephoneNumber@13fee20c] . then a trie print a 2 fields each Telephone and appears NULL – Gui Pinto May 16 '16 at 14:59
0

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);
andrucz
  • 1,971
  • 2
  • 18
  • 30