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

时间:2022-06-22
本文章向大家介绍使用java将json文件反序列化成java对象,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

版权声明:本文为博主汪子熙原创文章,未经博主允许不得转载。 https://jerry.blog.csdn.net/article/details/89818811

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

}

要获取更多Jerry的原创文章,请关注公众号"汪子熙":