开发者

What’s the best way to load a JSONObject from a json text file?

What would be the easiest way to load a file containing JSON into a JSONObject.

At the moment I am using json-lib.

This is what I have, but it throws an exc开发者_如何学Ception:

XMLSerializer xml = new XMLSerializer();
JSON json = xml.readFromFile("samples/sample7.json”);     //line 507
System.out.println(json.toString(2));

The output is:

Exception in thread "main" java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
    at net.sf.json.xml.XMLSerializer.readFromStream(XMLSerializer.java:386)
    at net.sf.json.xml.XMLSerializer.readFromFile(XMLSerializer.java:370)
    at corebus.test.deprecated.TestMain.main(TestMain.java:507)


Thanks @Kit Ho for your answer. I used your code and found that I kept running into errors where my InputStream was always null and ClassNotFound exceptions when the JSONObject was being created. Here's my version of your code which does the trick for me:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;

import org.json.JSONObject;
public class JSONParsing {
    public static void main(String[] args) throws Exception {
        File f = new File("file.json");
        if (f.exists()){
            InputStream is = new FileInputStream("file.json");
            String jsonTxt = IOUtils.toString(is, "UTF-8");
            System.out.println(jsonTxt);
            JSONObject json = new JSONObject(jsonTxt);       
            String a = json.getString("1000");
            System.out.println(a);   
        }
    }
}

I found this answer to be enlightening about the difference between FileInputStream and getResourceAsStream. Hope this helps someone else too.


try this:

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils; 

    public class JsonParsing {

        public static void main(String[] args) throws Exception {
            InputStream is = 
                    JsonParsing.class.getResourceAsStream( "sample-json.txt");
            String jsonTxt = IOUtils.toString( is );

            JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );        
            double coolness = json.getDouble( "coolness" );
            int altitude = json.getInt( "altitude" );
            JSONObject pilot = json.getJSONObject("pilot");
            String firstName = pilot.getString("firstName");
            String lastName = pilot.getString("lastName");

            System.out.println( "Coolness: " + coolness );
            System.out.println( "Altitude: " + altitude );
            System.out.println( "Pilot: " + lastName );
        }
    }

and this is your sample-json.txt , should be in json format

{
 'foo':'bar',
 'coolness':2.0,
 'altitude':39000,
 'pilot':
     {
         'firstName':'Buzz',
         'lastName':'Aldrin'
     },
 'mission':'apollo 11'
}


With java 8 you can try this:

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class JSONUtil {

    public static JSONObject parseJSONFile(String filename) throws JSONException, IOException {
        String content = new String(Files.readAllBytes(Paths.get(filename)));
        return new JSONObject(content);
    }

    public static void main(String[] args) throws IOException, JSONException {
        String filename = "path/to/file/abc.json";
        JSONObject jsonObject = parseJSONFile(filename);

        //do anything you want with jsonObject
    }
}


Another way of doing the same could be using the Gson Class

String filename = "path/to/file/abc.json";
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
SampleClass data = gson.fromJson(reader, SampleClass.class);

This will give an object obtained after parsing the json string to work with.


On Google'e Gson library, for having a JsonObject, or more abstract a JsonElement:

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

JsonElement json = JsonParser.parseReader( new InputStreamReader(new FileInputStream("/someDir/someFile.json"), "UTF-8") );

This is not demanding a given Object structure for receiving/reading the json string.

Edit 2021-May-13: As I commented myself: This solution does not properly take care of closing streams!
This does:

JsonElement json = null;
try (Reader reader = new InputStreamReader(new FileInputStream("/someDir/someFile.json"), "UTF-8")) {
    json = JsonParser.parseReader( reader );
} catch (Exception e) {
    // do something
}

As one can see the code gets bloated when doing correctly. I would clean-code move the 'loading of a json from a file' into a FileUtils.class; which probably already exists and does super nice adjustable Exception handling...


Example of json which I am using:

"identity" : {
  "presentProvince" : [ {
    "language" : "eng",
    "value" : "China"
  } ],
  "presentAddressLine1" : [ {
    "language" : "eng",
    "value" : "bjbjbhjbhj"
  } ],
 "permanentAddressLine4" : [ {
    "language" : "eng",
    "value" : "123456"
  } ]
} } 

Here is the code to access language and value:

public static void JsonObjParsing() throws Exception {
    File f = new File("id.json");
    if (f.exists()){
        InputStream is = new FileInputStream(f);
        String jsonTxt = IOUtils.toString(is, "UTF-8");
        System.out.println(jsonTxt);
            
            
        JSONObject json = new JSONObject(jsonTxt); 
           
        JSONObject identity = json.getJSONObject("identity");
            
            
        JSONArray identityitems = identity.getJSONArray("presentProvince");
        for (Object o : identityitems) {
            JSONObject jsonLineItem = (JSONObject) o;
            String language = jsonLineItem.getString("language");
            String value = jsonLineItem.getString("value");
            System.out.println(language +" " + value);
        }
    } 
}


public static void main(String[] args) throws Exception {
    JsonObjParsing();
}


A way of getting both array of json in file or simply json would be

InputStream inputStream= Employee.class.getResourceAsStream("/file.json");
CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(List.class, Employee.class);

List<Employee> lstEmployees = mapper.readValue(inputStream, collectionType);

The file.json needs to be placed in the resources folder. If your file only has a json block without json array square brackets [] , you can skip the CollectionType

InputStream inputStream= Employee.class.getResourceAsStream("/file.json");
Employee employee = mapper.readValue(inputStream, Employee.class);

Also refer here for original answer from where I have drawn.


import org.springframework.transaction.annotation.Transactional;
import org.springframework.core.io.ByteArrayResource;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.File;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.minidev.json.JSONObject;
    
    String filename = "xyz.json";
    
    @Transactional
        public Object getFileInternalJsonData(String filename) {
            try {
                ByteArrayResource inputStream = new ByteArrayResource(Files.readAllBytes(Paths.get("D:\MyData\test\" + File.separator + filename)));
                return new ObjectMapper().readValue(inputStream.getInputStream(), Object.class);
            } catch (Exception e) {
                return new JSONObject().appendField("error", e.getMessage());
            }
        }


You can try the below code, the main advantage for this code is you don't need to use any external dependency like org.json.simple

String resourceName = "response.json";
        //InputStream is = JSONMapperImpl.class.getResourceAsStream(resourceName);
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        InputStream resourceStream = loader.getResourceAsStream(resourceName);
        if (resourceStream == null) {
            throw new NullPointerException("Cannot find resource file " + resourceName);
        }

        JSONTokener tokenizer = new JSONTokener(resourceStream);
        JSONObject object = new JSONObject(tokenizer);

If you are facing any dependency issue then please add below dependency in your pom.xml file

    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20220924</version>
    </dependency>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜