0

How to convert a JsonArrayString to List<String> or String[]? I tried to use Gson to covert it, but I failed. Maybe I overlooked some existing methods which can do this? Any other better way to make it or can someone give me some tips?

[
    {
        "test": "test"
    },
    {
        "test": "test"
    },
    {
        "test": "test",
        "test2": "test2",
        "test3": [
            {
                "test": "test"
            },
            {
                "test": "test"
            }
        ]
    }
]
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
gann yee
  • 121
  • 2
  • 7
  • Please refer to this http://stackoverflow.com/questions/15871309/convert-jsonarray-to-string-array after validating your json data in http://www.jsoneditoronline.org/ – Jeffin Manuel Mar 21 '17 at 02:46

2 Answers2

0

I guess you dont know if the value is a JSONObject or a JSONArray. In thise case you may want to use a Map and a Object as Value like this (not tested).

class Model { 
  private Map<String, Object> test;
}

Take care that you have to validate if the Value is a JSONArray or a JSONObject using (for example):

if (this.getTest().getValue() instanceof JSONObject.class) { ... }
Emanuel
  • 8,027
  • 2
  • 37
  • 56
0

I Finally find the way to resovel:

    // Converting JSON String array to Java String array
    String jsonStringArray = "[{\"test\":\"test1\"},{\"test\":\"test2\"},{\"test\":\"test3\",\"test2\":[{\"test\":\"test1\"},{\"test\":\"test2\"}]}]";

    // creating Gson instance to convert JSON array to Java array
    Gson converter = new Gson();

    Type type = new TypeToken<List>() {
    }.getType();
    List list = converter.fromJson(jsonStringArray, type);

    // convert List to Array in Java

    System.out.println("Java List created from JSON String Array - example");
    System.out.println("JSON String Array : " + jsonStringArray);
    System.out.println("Java List : " + list);

    // let's now convert Java array to JSON array -
    String toJson = converter.toJson(list);
    System.out.println("Json array created from Java List : " + toJson);

output:

Java List created from JSON String Array - example
JSON String Array : [{"test":"test1"},{"test":"test2"},    
{"test":"test3","test2":[{"test":"test1"},{"test":"test2"}]}]
Java List : [{test=test1}, {test=test2}, {test=test3, test2=[{test=test1},   {test=test2}]}]
Json array created from Java List : [{"test":"test1"},{"test":"test2"},{"test":"test3","test2":[{"test":"test1"},{"test":"test2"}]}]
gann yee
  • 121
  • 2
  • 7