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);
Flavio
  • 895
  • 3
  • 14
  • 19

1 Answers1

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]
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • @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. – Sotirios Delimanolis Apr 04 '14 at 22:41