1
((JSONArray) JsonUtils.parseStringToJsonObject(response.getResponseBody()).get("firstArray")).stream()
                .map(s->((JSONArray) s).get(1).toString()).collect(Collectors.toList())

Why is this code snippet will return an Object and not a List?

(response type is a IHttpResponse<String>)

shmosel
  • 49,289
  • 6
  • 73
  • 138
Twi
  • 765
  • 3
  • 13
  • 29
  • You're casting it to Object? `(JSONArray)`... is this an object? – zlakad Feb 15 '18 at 16:26
  • Which JSONArray is this? (It's not a Java API class. You should add the appropriate tag.) – DodgyCodeException Feb 15 '18 at 16:45
  • I am using org.json.simple. This JSONArray is from here: https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1 – Twi Feb 16 '18 at 08:55
  • A `List` is an `Object`? I don't get the problem. Can you elaborate and add more code? – Steffen Harbich Feb 16 '18 at 09:08
  • So the problem is -> When I want to return in a method with this code snippet, it will return Object and not a List. I want to return a List, but it doesn't allow to do this. – Twi Feb 16 '18 at 09:24
  • Die you see that it is of type _object_ while debuging or did you get an Error while casting your result? The return-type sould be _List_. Did you try to assign the result to a variable? – Michael Seiler Feb 20 '18 at 16:22
  • Before compiling the IDE doesn't let me to write down this statement, that I want to return this statement as a List. Also when I debugging it I saw it that the lambda expression will be an Object every case, even if I cast it to String with toString. – Twi Feb 20 '18 at 16:24

1 Answers1

0

Following code should work

Sample code to initialize the JSONArray

    JSONArray jsonArray =new JSONArray();
    JSONObject j1 = new JSONObject();
    j1.put ("key", "Stack");
    JSONObject j2 = new JSONObject();
    j2.put ("key", "Overflow");
    jsonArray.add(j1);
    jsonArray.add(j2);

Convert the JSONArray to List. There were couple of issues in your code. The first one being, you were using JSONArray inside your map function and it should be JSONObject . The second one is, map returns Stream and we need to typecast it to Stream<String>

 List<String> output =  arrayToStream(jsonArray)
                                 .map(JSONObject.class::cast)
                                 .map(s -> s.get("key").toString())
                                 .collect(Collectors.toList());

Util method to convert JSONArray to Stream<Object>

private static Stream<Object> arrayToStream(JSONArray array) {
        return StreamSupport.stream(array.spliterator(), false);
    }
CGS
  • 2,782
  • 18
  • 25