-1

I have a request which gets a response like this one right here:

[
  [
    {
      "id": 0,
      "name": "xxxx"
    },
    {
      "id": 1,
      "name": "yyyy"
    },
  ]
]

As you can see, the objects are "encapsulated" and the only way I've found to parse them is this:

private static final TypeReference<List<List<Map<String, Object>>>> test = new TypeReference<List<List<Map<String, Object>>>>() {};

public List<List<Map<String, Object>>> getTransactions() throws IOException {
    return mapper.convertValue(send("/someapi/), test);
}

This seems very inconvenient because to access the objects I have to ".get(i).get(j)".. Is this actually the way to do it or am I doing it wrong?

M. Malkon
  • 145
  • 1
  • 6
  • 3
    JSON objects can have two properties with the same name? [OMG, it's true](https://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object) – Thomas Weller Jul 23 '18 at 21:19
  • I'm pretty sure any kind of conversion to an object will fail, for there's a key collision.. anyway.. you will probably prefer using Gson library, you can convert json to an object easily using that library – Hagai Wild Jul 23 '18 at 21:21
  • oh damn, sorry. that was a mistake. They dont have the same name – M. Malkon Jul 23 '18 at 21:28
  • So the JSON has array of array of objects, and you're asking if you really have to `get` from both JSON arrays? Of course you do. How else would you get to the objects? – Andreas Jul 23 '18 at 21:33
  • List>> just seemed to inelegant to me. If that's what it takes, I'm good. – M. Malkon Jul 23 '18 at 21:53

1 Answers1

0

If you don't want to deserialize everything into Java objects, you can use JsonPath and the JayWay implementation. You basically use a String path to tell the parser what you want. Here is a test, where the path to get the name of the second JSON object is $[0][1].name

import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class JsonPathTest {

    private final String json = "[\n" +
            "  [\n" +
            "    {\n" +
            "      \"id\": 0,\n" +
            "      \"name\": \"xxxx\"\n" +
            "    },\n" +
            "    {\n" +
            "      \"id\": 1,\n" +
            "      \"name\": \"yyyy\"\n" +
            "    }\n" +
            "  ]\n" +
            "]";

    @Test
    public void testIt() {
        DocumentContext jsonContext = JsonPath.parse(json);
        String secondNamePath = "$[0][1].name";
        String name = jsonContext.read(secondNamePath);

        assertEquals("yyyy", name);
    }
}

You need to add the dependency

    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>2.1.0</version>
    </dependency>

See also:

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720