且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用java将json文件反序列化成java对象

更新时间:2022-09-11 10:09:07

package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

public class testJson {

    /**
     * @param args
     */
    public static void main(String[] args) 
    {
        String path = "C:\\Users\\i042416\\Desktop\\1.txt";
        File file = new File(path);
        StringBuffer buffer = new StringBuffer();
        InputStreamReader read;
        try 
        {
            read = new InputStreamReader( new FileInputStream(file));
            BufferedReader bufferedReader = new BufferedReader(read); 
            String lineTxt = null; 
            while((lineTxt = bufferedReader.readLine() ) != null)
            { 
                buffer.append(lineTxt);
            } 
            read.close(); 
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
        System.out.println("content: " + buffer.toString());
        JSON json = JSONSerializer.toJSON(buffer.toString());   
        JSONObject jsonObject = JSONObject.fromObject(json);
        JSONArray array = jsonObject.getJSONArray("statuses");
        int size = array.size();
        System.out.println("total post number: " + size);
        for( int i = 0; i < size; i++)
        {
            JSONObject post = array.getJSONObject(i);
            System.out.println("****************************************************");
            System.out.println("Post Index: " + i);
            String id = post.getString("idstr");
            System.out.println("Post ID: " + id);
            System.out.println("Post content: " + post.getString("text"));
            System.out.println("Created at: " + post.getString("created_at"));
            JSONObject user = array.getJSONObject(i).getJSONObject("user");
            System.out.println("user ID: " + user.getString("idstr"));
            System.out.println("name: " + user.getString("name"));
        }
    }

}