首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用java将json文件反序列化成java对象

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

作者头像
Jerry Wang
发布2019-05-30 13:05:28
1.9K0
发布2019-05-30 13:05:28
举报

版权声明:本文为博主汪子熙原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1438744

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的原创文章,请关注公众号"汪子熙":

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年05月04日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档