-3

I have a json array as a string in the following format:

 [ "Ford", "BMW", "Fiat" ]

which is a legal json string. How am I able to use Gson to save into an object? When I am trying to use getAsJsonArray(), but I get an error:

 java.lang.IllegalStateException: This is not a JSON Array.
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Nir Ben Yaacov
  • 1,182
  • 2
  • 17
  • 33
  • Add your code and the complete stacktrace – Jens Mar 30 '17 at 11:43
  • check out http://stackoverflow.com/questions/19780576/parsing-json-array-resulting-in-this-is-not-a-json-array-exception it might help guide you – Takarii Mar 30 '17 at 11:45
  • take a look at this site : http://www.javatpoint.com/json-array and this : http://www.json.org/index.html – JHDev Mar 30 '17 at 11:46
  • `JsonArray jArray = new JsonParser().parse(jsonStr).getAsJsonArray();` works fine for me. If you got that exception this means that you are not parsing what you expect. Post proper [MCVE] (a.k.a. [SSCCE](http://sscce.org)) – Pshemo Mar 30 '17 at 11:52
  • I have added an example. I am unsure if this is what you are actually looking for? My solution it into String object since you only mentioned `an object`. Your question is vague, what object do you want to save it to? – kkflf Mar 30 '17 at 11:58

2 Answers2

0

Use Gson to parse your Json array.

String input = "[ 'Ford', 'BMW', 'Fiat' ]";

Gson gson = new Gson();
String[] output = gson.fromJson(input, String[].class);

for(String s : output){
    System.out.println(s);
}

Output

Ford
BMW
Fiat
kkflf
  • 2,435
  • 3
  • 26
  • 42
  • Thrown exception suggests that OP is not parsing valid JSON array, but what was posted in question is valid which suggests that problem is not *how* OP is parsing, but *what*. – Pshemo Mar 30 '17 at 11:59
0

You can use this to get value into arraylist using getAsJsonArray() Method

    String jsonStr = "['Ford', 'BMW', 'Fiat' ]";
    JsonArray root = new JsonParser().parse(jsonStr).getAsJsonArray();
    Gson gson = new Gson();
    ArrayList<String> staff = new ArrayList<>() ;
    Type listType = new TypeToken<List<String>>() {}.getType();
    List<String> yourList = new Gson().fromJson(root, listType);

    System.out.println(yourList );
Santy
  • 24
  • 3