简体   繁体   中英

java gson json object array to string array

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.

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
    }

 }

}

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