programing

json 텍스트 파일에서 JSONObject를 로드하는 가장 좋은 방법은 무엇입니까?

newnotes 2023. 3. 16. 21:48
반응형

json 텍스트 파일에서 JSONObject를 로드하는 가장 좋은 방법은 무엇입니까?

JSON이 포함된 파일을 JSONObject에 로드하는 가장 쉬운 방법은 무엇입니까?

지금은 json-lib을 사용하고 있습니다.

내가 가지고 있는 것은 이것입니다만, 예외는 다음과 같습니다.

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

출력은 다음과 같습니다.

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)

@Kit Ho 답변 감사합니다.코드를 사용했는데 JSONObject를 생성할 때 InputStream이 항상 늘이고 ClassNotFound 예외가 발생하는 오류가 계속 발생하였습니다.다음은 나에게 도움이 되는 코드 버전입니다.

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);   
        }
    }
}

답변은 FileInputStream과 getResourceAsStream의 차이에 대해 설명했습니다.이게 다른 사람에게도 도움이 되길 바라.

이것을 시험해 보세요.

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 );
        }
    }

그리고 이건 당신의 샘플 json입니다.txt 는 json 형식이어야 합니다.

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

Java 8 에서는, 다음의 조작을 실행할 수 있습니다.

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
    }
}

또 다른 방법은 Gson 클래스를 사용하는 것입니다.

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);

이렇게 하면 작업할 json 문자열을 구문 분석한 후 얻은 개체가 제공됩니다.

Google'e Gson 라이브러리에서JsonObject, 또는 보다 추상적인 aJsonElement:

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

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

json 문자열을 수신/읽기 위해 지정된 개체 구조가 필요하지 않습니다.

2021년 5월 13일 편집: 제 코멘트대로:이 솔루션은 닫히는 스트림을 제대로 처리하지 못합니다!
이것은 다음과 같습니다.

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

보시다시피 올바르게 하면 코드가 비대해집니다.파일로부터의 json의 로딩'을 FileUtils.class로 클리닝 코드 이동하겠습니다.이 클래스는 이미 존재하며 조정 가능한 예외 처리를 매우 훌륭하게 수행합니다.

사용하고 있는 json의 예:

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

다음은 언어와 가치에 액세스하기 위한 코드입니다.

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();
}

파일 또는 단순히 json의 두 배열을 모두 가져오는 방법은 다음과 같습니다.

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

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

file.json을 Resources 폴더에 배치해야 합니다.파일에 json 배열 대괄호 []가 없는 json 블록만 있는 경우 컬렉션을 건너뛸 수 있습니다.유형

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

또한 제가 그린 원본 답변에 대해서는 여기를 참조하십시오.

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());
            }
        }

아래 코드를 사용해 볼 수 있습니다.이 코드의 주된 장점은 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);

의존관계 문제가 있는 경우 pom.xml 파일에 다음과 같은 의존관계를 추가하십시오.

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

언급URL : https://stackoverflow.com/questions/7463414/what-s-the-best-way-to-load-a-jsonobject-from-a-json-text-file

반응형