-3

I have an a string like

String myString = "[\"One\", \"Two\"]";

I am struggling with figuring out how to turn it into an ArrayList with values "One" and "Two"

I tried using JSONArray but it doesn't seem to work how I expected


EDIT:" When I print my string it actually prints without the \

System.out.println(myString) prints:

["One", "Two"]

I tried

JSONArray jsonArr = new JSONArray(stringCharactersArray);

and got that the constructor can't take a string. I am using JSONArray from

    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1.1</version>
    </dependency>
es3735746
  • 841
  • 3
  • 16
  • 40

3 Answers3

1

If you want to parse your string with json-simple, then do the following:

String myString = "[\"One\", \"Two\"]";
JSONArray array = (JSONArray) new JSONParser().parse(myString);
System.out.println(array);

This prints out:

["One","Two"]

If you want to have it as a java.util.List then simply do the following:

String myString = "[\"One\", \"Two\"]";
List<String> list = Arrays.asList(myString.replaceAll("[\\[\\]]", "").split(", "));
System.out.println(list);

This prints out:

["One", "Two"]
Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66
0

I ran your code and it's working fine BUT instead of using com.googlecode.json-simple I used org.json.JSONArray:

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

and the code:

import org.json.JSONArray;

public class Test {
    public static void main(String[] args) {
        String val = "[\"One\", \"Two\"]";
        
        JSONArray jsonArr = new JSONArray(val);  
        for (int i = 0; i < jsonArr.length(); i++) {
            System.out.println( jsonArr.getString( i ) );
        }
    }
}

this prints:

One

Two

It seems that it doesn't need the input string json array to be exactly formed as standard as:

{"arr": ["One", "two"]}.

Hope this helps.

Community
  • 1
  • 1
STaefi
  • 4,297
  • 1
  • 25
  • 43
0

You can try this one. I used "org.json"

String myString = "[\"One\", \"Two\"]";
try {
    JSONArray jsonArray = new JSONArray(myString);
    for (int i = 0; i < jsonArray.length(); i++) {
        System.out.println(jsonArray.getString(i));
    }
} catch (JSONException e) {
    e.printStackTrace();
} 

It would print.

One
Two
Rowi
  • 545
  • 3
  • 9