java gson json对象数组到字符串数组
我是JAVA初学者,正在使用gson库转换JSON字符串,如下所示:java gson json对象数组到字符串数组,java,gson,Java,Gson,我是JAVA初学者,正在使用gson库转换JSON字符串,如下所示: 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\",\"
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);
但问题是我需要将“customernames”数组作为字符串数组而不是对象数组返回
gson能做到这一点吗?还是必须在以后通过某种方式检测类型(数组),然后在每个元素上循环,将其转换为字符串数组并替换对象数组
增加的问题是JSON字段名不是固定的,JSON字符串中可能包含多个数组,所有数组都需要转换。您可以使用jsonarray获取特定字段名 您可以找到json api 将json文本添加到文件中,或者可以使用缓冲区传递给参数
String json = "{\"customer_names\" : [...]}";
然后
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());
}
感谢您的帮助,问题是我需要能够将所有数组转换为字符串数组,并且json字段名称不固定。您可以检查返回的对象是否为数组实例,然后转换为字符串数组检查此链接
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
}
}
}