2011-10-05 6 views
1

json 파일 ("twitter-feed.json") 형태로 일부 트위터 피드를 얻으려면 cURL을 사용했습니다. 이 json 파일을 JSONArray 객체로 변환하고 싶습니다. 어떻게해야합니까?.json 파일을 JSONArray로 변환

Java 및 json을 처음 사용합니다. 귀하의 제안을 환영합니다.

FileInputStream infile = new FileInputStream("input/twitter-feed.json"); 

// 파싱 JSON JSONArray jsonArray = 새로운 JSONArray (캐릭터에게);

// use 
    for (int i = 0; i < jsonArray.length(); i++) { 
     JSONObject jsonObject = jsonArray.getJSONObject(i); 

     System.out.println(jsonObject.getString("id")); 
     System.out.println(jsonObject.getString("text"));    
     System.out.println(jsonObject.getString("created_at"));  
    } 

감사합니다, PD.

답변

0

당신은 Gson을 시도 할 수 있습니다 :

그냥 배열을 사용할 수 :

Gson gson = new Gson(); 

//(Deserialization) 
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); 

이 객체의 배열을 직렬화하기 위해, 당신은 할 수 있습니다 :

Container container = new Gson().fromJson(json, Container.class); 

shown here을 따라

1

너 파일을 먼저 읽고 나서 String으로 변환 한 다음 JSONArray으로 피드하십시오 (나는 JSON-Java Project을 사용하고 있다고 가정합니다).

  • 스트림 API는 전체 유효 JSON을 제공하지 않습니다하지만 delimited field에 의해 지정된 오히려 유효한 하나를 아래의 코드는 파일을 읽고 JSONArray

    
    // read the source file, source comes from streaming API delimited by newline 
    // done by curl https://stream.twitter.com/1/statuses/sample.json?delimited=newline -utwitterUsername:twitterPasswd 
    // > /Projects/StackOverflow/src/so7655570/twitter.json 
    FileReader f = new FileReader("/Projects/StackOverflow/src/so7655570/twitter.json"); 
    BufferedReader br = new BufferedReader(f); 
    
    ArrayList jsonObjectArray = new ArrayList(); 
    String currentJSONString = ""; 
    
    // read the file, since I ask for newline separation, it's easier for BufferedReader 
    // to separate each String 
    while((currentJSONString = br.readLine()) != null) { 
        // create new JSONObject 
        JSONObject currentObject = new JSONObject(currentJSONString); 
    
        // there are more than one way to do this, right now what I am doing is adding 
        // each JSONObject to an ArrayList 
        jsonObjectArray.add(currentObject); 
    } 
    
    for (int i = 0; i < jsonObjectArray.size(); i++) { 
        JSONObject jsonObject = jsonObjectArray.get(i); 
    
        // check if it has valid ID as delete won't have one 
        // sample of JSON for delete : 
        // {"delete":{"status":{"user_id_str":"50269460","id_str":"121202089660661760","id":121202089660661760,"user_id":50269460}}} 
    
        if(jsonObject.has("id")) { 
         System.out.println(jsonObject.getInt("id")); 
         System.out.println(jsonObject.getString("text"));    
         System.out.println(jsonObject.getString("created_at") + "\n");  
        } 
    } 
    

    단계 설명으로 설정하는 방법을 보여줍니다. 그래서, 전체 결과를 그대로 파싱 할 수는 없습니다. JSON을 구문 분석하기 위해

  • , 나는 BufferedReader이 방법 나는 각 라인에서 각각의 유효한 JSON을 일단 우리가 직접 각각 된 JSONObject
  • 를 얻기 위해 사용할 수 readLine이 있기 때문에 newline을 사용하여, 나는 JSONObject를 작성하고 추가 할 delimited를 사용 it to the ArrayList
  • 그런 다음 ArrayList에있는 각 JSONObject을 반복하여 결과를 인쇄하십시오.

// read the source file, source comes from streaming API 
// done by curl https://stream.twitter.com/1/statuses/sample.json?delimited=newline -utwitterUsername:twitterPasswd 
// > /Projects/StackOverflow/src/so7655570/twitter.json 
FileReader f = new FileReader("/Projects/StackOverflow/src/so7655570/twitter.json"); 
BufferedReader br = new BufferedReader(f); 

String currentJSONString = ""; 

// read the file, since I ask for newline separation, it's easier for BufferedReader 
// to separate each String 
while((currentJSONString = br.readLine()) != null) { 
    // create new JSONObject 
    JSONObject currentObject = new JSONObject(currentJSONString); 

    // check if it has valid ID as delete status won't have one 
    if(currentObject.has("id")) { 
     System.out.println(currentObject.getInt("id")); 
     System.out.println(currentObject.getString("text"));    
     System.out.println(currentObject.getString("created_at") + "\n");  
    } 
} 
:에 코드를 변경 ArrayList에 저장하지 않고 즉시 결과를 사용하고자하고 나중에 사용할 필요가없는 경우, 당신은 동안 루프에서 처리 자체를 할 수 있습니다 이 같은
+0

감사 모모 귀하의 제안합니다. 나는 그것을 시도하고이 오류가 발생합니다 : "main"스레드의 예외 java.text.ParseException : "JSONArray는 '['1의 문자에서 시작해야합니다."내 json 파일은 {로 끝나고}로 시작합니다. 이것을 배열로 변환하는 방법이 있어야합니다 .... – user979511

+0

즉, 입력이 올바르지 않습니다. http://twitter.com/statuses/user_timeline/109531911.json과 같은 URL을 통해 JSON 입력을 받고 답변을 게시하기 전에 테스트했습니다. 입력/twitter-feed.json에서 입력의 일부를 복사하여 붙여 넣을 수 있습니까?'[' – momo

+0

또한 트위터 피드의 소스를 얻을 수 있습니까? 다른 JSON 피드가있는 것보다 다른 소스에서 가져온 것일 수도 있습니다. – momo

0

사용 ObjectMapper 클래스 잭슨에서 라이브러리 :

//JSON from file to Object 
Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class); 

//JSON from URL to Object 
Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class); 

//JSON from String to Object 
Staff obj = mapper.readValue(jsonInString, Staff.class);