-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.
5
  • Add your code and the complete stacktrace Commented Mar 30, 2017 at 11:43
  • check out stackoverflow.com/questions/19780576/… it might help guide you Commented Mar 30, 2017 at 11:45
  • take a look at this site : javatpoint.com/json-array and this : json.org/index.html Commented Mar 30, 2017 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 minimal reproducible example (a.k.a. SSCCE) Commented Mar 30, 2017 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? Commented Mar 30, 2017 at 11:58

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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 );

1 Comment

Remove unnecessary things

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.