0

I'm trying to get translation from web dictionary. Here is a piece of Json which I want to parse using JsonNode.

{
"result" : "ok",
"tuc" : [ {
"phrase" : {
  "text" : "powitanie",
  "language" : "pl"
}      

and java code:

try {

        JsonNode node = translationMapper.readTree(jsonContent);
        String result = node.get("result").asText();
        System.out.println("result: " + result);
        JsonNode tuc = node.get("tuc").get(0);
        JsonNode phrase = tuc.get("phrase").get(0);
        String textPhrase = phrase.get("text").asText();
        System.out.println("translation: " + textPhrase);

    }

    catch (IOException e) {
        e.printStackTrace();
    }

output:

result: ok

Exception in thread "main" java.lang.NullPointerException at Requests.main(Requests.java:63)

line 63 is:

String textPhrase = phrase.get("text").asText();
James121
  • 81
  • 10
  • `phrase` is not a JSON array. `.get("phrase").get(0)` will return `null`. – Sotirios Delimanolis Feb 20 '18 at 19:59
  • @SotiriosDelimanolis, but here you didn't have to use JsonArray and it worked. https://stackoverflow.com/questions/15035855/using-jackson-json-parser-complex-json – James121 Feb 21 '18 at 07:52
  • I'm not talking about the type `JsonArray`. `JsonNode#get(int)` returns `null` if the underlying JSON element isn't a JSON array. In the link you posted, it is in. In your code, it isn't. – Sotirios Delimanolis Feb 21 '18 at 14:41
  • @SotiriosDelimanolis Ok, thank you. So 'phrase' is JSON object? How to get the object from Json? – James121 Feb 22 '18 at 15:05
  • If you read the Javadoc for `JsonNode`, you'll see a bunch of `isObject`, `isArray`, etc. methods for determining the underlying type of the json element. Use those to find out what you're working with and then cast each node to its corresponding type, `ObjectNode`, `ArrayNode`, etc. – Sotirios Delimanolis Feb 22 '18 at 15:57

0 Answers0