简体   繁体   中英

How to retrieve value from JSON using java

I like to get the value of code from below JSON but I am getting an error like below:-

java.lang.NullPointerException

I am getting an error in below line of code

 Iterator<String> iterator = companyList.iterator();

I have JSON object like below:-

{
    "products":
    {
        "productsApp13": {
            "code": "productsApp13",
            "name": "productsApp13",
            "attribute_set": "Apparel",
            "product_type": "product",
            "status": "active"
            }
    }
}

My code:-

import org.junit.Before;
import org.junit.Test;

import com.fasterxml.jackson.databind.ObjectMapper;

import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

 try {

                Object obj1 = parser.parse(new FileReader(path.directorypath));
                JSONObject jsonObject = (JSONObject) obj1;

                String name = (String) jsonObject.get("products").toString();
                System.out.println("Testing Parse Value = "+name);
                request.payload = name;


                JSONArray companyList = (JSONArray) jsonObject.get("code");
                Iterator<String> iterator = companyList.iterator();
                while (iterator.hasNext()) {
                    System.out.println(iterator.next());
                }

I know that productsApp13 or code key is not an array while I am not able to identify any method to read this particular value.

Moreover, I also want to know that how can I modify this value for my payload

This minimal example works for me:

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;
import java.io.StringReader;

public class Main {

    public static void main(String[] args) {
        final JsonReader jsonReader = Json.createReader(new StringReader("{\n" +
                "    \"products\":\n" +
                "    {\n" +
                "        \"productsApp13\": {\n" +
                "            \"code\": \"productsApp13\",\n" +
                "            \"name\": \"productsApp13\",\n" +
                "            \"attribute_set\": \"Apparel\",\n" +
                "            \"product_type\": \"product\",\n" +
                "            \"status\": \"active\"\n" +
                "            }\n" +
                "    }\n" +
                "}"));
        final JsonObject jsonObject = jsonReader.readObject();

        final JsonValue products = jsonObject.get("products");
        final JsonValue productsApp13 = ((JsonObject) products).get("productsApp13");
        final JsonValue code = ((JsonObject) productsApp13).get("code");

        System.out.println("code = " + code); // code = "productsApp13"
    }
}

To get access to javax.json.* I use the Maven dependency

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.0.4</version>
</dependency>

try following hope it fix your problem

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.json.JSONObject;

public class Main {
    public static void main(final String[] args) throws Exception {

        final JSONObject jsonObject = new JSONObject(getResponseAsString(getFilePath()));
        final JSONObject products = jsonObject.getJSONObject("products");

        final String name = products.toString();
        System.out.println("Testing Parse Value = " + name);

        final JSONObject productsApp13 = products.getJSONObject("productsApp13");

        final String code = productsApp13.getString("code");

        System.out.println("code value : " + code);

    }

    private static Path getFilePath() throws URISyntaxException, FileNotFoundException {
        URL url = Main.class.getClassLoader().getResource("jsonFile.txt");
        if (url == null) {
            throw new FileNotFoundException();
        }
        return Paths.get(url.toURI());
    }

    private static String getResponseAsString(final Path filePath) throws FileNotFoundException, IOException {
        return new String(Files.readAllBytes(filePath));
    }
}

Maven dependency to compile above

<dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20131018</version>
    </dependency>

Code worked for me:-

        FileReader reader = new FileReader(filePath);

        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

        JSONObject jsonObject1 = (JSONObject) jsonObject.get("products");
        JSONObject jsonObject2 = (JSONObject)jsonObject1.get("productsApp15");
        String firstName = (String) jsonObject2.get("code").toString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM