0

I have a json file.

{
    "data" : [
        "my/path/old",
        "my/path/new"
    ]
}

I need to conver it to ArrayList of String. How to do it using Jackson library?

UPD:

My code:

Gson gson = new Gson();        
JsonReader reader = new JsonReader(new InputStreamReader(FileReader.class.getResourceAsStream(file)));

List<String> list = (ArrayList) gson.fromJson(reader, ArrayList.class);

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

And my exception:

Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected value at line 1 column 1

My new update

UPD2:

Gson gson = new Gson();
Type list = new TypeToken<List<String>>(){}.getType();
JsonReader reader = new JsonReader(new InputStreamReader(FileReader.class.getResourceAsStream(file)));
List<String> s = gson.fromJson(reader, list);
System.out.println(s);
8
  • possible duplicate of How to convert the following json string to java object? Commented Apr 4, 2014 at 21:42
  • They using GSON and JSR 353. Commented Apr 4, 2014 at 21:44
  • Look at the first answer. Commented Apr 4, 2014 at 21:45
  • The correct answer is using jackson @Flavio Commented Apr 4, 2014 at 21:45
  • 1
    Your JSON is an object, not an array. There's no obvious way to convert it to a List. Do you want the array named data? Commented Apr 4, 2014 at 21:53

1 Answer 1

4

You've tagged Jackson but are using Gson in your example. I'm going to go with Jackson

String json = "{\"data\":[\"my/path/old\",\"my/path/new\"]}"; // or wherever you're getting it from

Create your ObjectMapper

ObjectMapper mapper = new ObjectMapper();

Read the JSON String as a tree. Since we know it's an object, you can cast the JsonNode to an ObjectNode.

ObjectNode node = (ObjectNode)mapper.readTree(json);

Get the JsonNode named data

JsonNode arrayNode = node.get("data");

Parse it into an ArrayList<String>

ArrayList<String> data = mapper.readValue(arrayNode.traverse(), new TypeReference<ArrayList<String>>(){});

Printing it

System.out.println(data);

gives

[my/path/old, my/path/new]
Sign up to request clarification or add additional context in comments.

1 Comment

@Flavio Are you sure your JSON is well formed? You might want to convert it to a String and print it out before passing it to your ObjectMapper. Also I was using Jackson 2. You might wish to upgrade.

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.