簡體   English   中英

將.json文件轉換為JSONArray

[英]Convert a .json file to a JSONArray

我使用cURL以json文件(“ twitter-feed.json”)的形式獲取了一些twitter feed。 我想將此json文件轉換為JSONArray對象。 我該怎么做?

我是Java和json的新手。 歡迎您提出建議。

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

//解析JSON JSONArray jsonArray = new JSONArray(string);

    // 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。

您需要先閱讀文件,將其轉換為String然后將其輸入JSONArray (我假設您正在使用JSON-Java Project 。以下代碼說明了如何讀取文件並將其設置為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");    
    }
}

步驟說明:

  • Stream API整體上不提供有效的JSON,而是由delimited字段指定的有效的JSON。 這就是為什么您不能按原樣解析整個結果。
  • 為了解析JSON,我使用delimited使用newline因為BufferedReader具有readLine方法,我們可以直接使用該方法獲取每個JSONObject
  • 從各行獲得每個有效的JSON之后,我將創建JSONObject並將其添加到ArrayList中
  • 然后,我迭代ArrayList每個JSONObject並打印出結果。 請注意,如果要立即使用結果,而不必以后再使用它,則可以在while循環中進行處理本身,而無需將其存儲在ArrayList ,后者將代碼更改為:

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

使用jackson庫中的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);

您可以嘗試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);

如圖所示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM