1

I am a beginner with JAVA and are using the gson library to convert a JSON string something like this:

String json = "{\"Report Title\": \"Simple Embedded Report Example with Parameters\",\"Col Headers BG Color\": \"yellow\",\"Customer Names\":[\"American Souvenirs Inc\",\"Toys4GrownUps.com\",\"giftsbymail.co.uk\",\"BG&E Collectables\",\"Classic Gift Ideas, Inc\"]}";
Gson gson = new Gson();
jsonObject (Map) = gson.fromJson(json, Object.class);

But the problem is I need the "Customer Names" array to be returned as a string array and not an object array.

Can gson do this or would it have to be converted afterwards by somehow detecting the type (array) and then looping over each element converting it to a string array and replacing the object array ?

The added problem is that the JSON field names are not fixed, and there may be multiple arrays contained in the JSON string and all of them need converting.

crankshaft
  • 2,607
  • 4
  • 45
  • 77

1 Answers1

1

you can use jsonarray to get specific field

you can find json api JSON

add json text into file or you can use buffer to pass to parameter

String json = "{\"customer_names\" : [...]}";   

then

JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("test.json"));

    JSONObject jsonObject = (JSONObject) obj;
         JSONArray msg = (JSONArray) jsonObject.get("Customer Names");
            Iterator<String> iterator = msg.iterator();
            while (iterator.hasNext()) {
                    System.out.println(iterator.next());
            }

or you can use GSON something like this

public class JsonPojo {
private String[] customer_names;
public String[] getCustomerNames(){ return this.customer_names;}
}


public class App{

 public static main(String[] args) {

 Gson gson = new Gson();
    JsonPojo thing = gson.fromJson(json, JsonPojo.class);
    if (thing.getCustomerNames()!= null)
    {
      // do what you want
    }

 }

}
Mithat Konuk
  • 447
  • 5
  • 19
  • Thanks for helping, the problem is I need to be able to convert all arrays into string arrays and the json field names are not fixed. – crankshaft Aug 07 '16 at 11:54
  • you can check with returned object is array instance then convert to String array check this link http://stackoverflow.com/questions/2725533/how-to-see-if-an-object-is-an-array-without-using-reflection – Mithat Konuk Aug 07 '16 at 11:58