gpt4 book ai didi

java - Java中使用Gson解析Json

转载 作者:行者123 更新时间:2023-11-30 04:38:24 26 4
gpt4 key购买 nike

我正在尝试解析本地 json 文件,但输出不是它应该显示的内容。我对 Json(和 Gson)缺乏经验,所以我不清楚问题是什么。

这是 tweet 类:

    public class tweet {
String from_user;
String from_user_name;
String profile_image_url;
String text;

public tweet(){
//empty constructor
}
}

这是使用Gson的类:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import com.google.gson.Gson;

public class tweetfeedreader {
public static void main(String args[]) throws FileNotFoundException {
Gson gson = new Gson();
BufferedReader bufferedReader = new BufferedReader(new FileReader(
"C:/Users/LILITH/Desktop/jsonfile.json"));
tweet J_tweet = gson.fromJson(bufferedReader, tweet.class);
System.out.println(J_tweet);
}
}

最后,我保存到本地目录的 .json 文件: http://search.twitter.com/search.json?q=%40android

没有错误,但输出是:

tweet@3030d5aa

我不确定可能出了什么问题,所以感谢您的指导!

[编辑:我忘了补充一下,我之前已经搜索过并阅读了相关帖子。它们可能很相似,但我没有太多运气将这些碎片拼凑在一起。]

最佳答案

从该 json 中删除结果数组,在 [] 之外不留下任何内容。

那么这就是我至少可以修改代码以使其正常工作的方法:

import java.lang.reflect.*;
import java.io.*;
import java.util.*;
import com.google.gson.*;
import com.google.gson.reflect.*;

public class tweetfeedreader {
public static void main(String args[]) throws IOException {
Gson gson = new Gson();
BufferedReader bufferedReader = new BufferedReader(new FileReader(
"jsonfile.json"));
String line;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) sb.append(line);
Type tweetCollection = new TypeToken<Collection<tweet>>(){}.getType();
Collection<tweet> tweets = gson.fromJson(line, tweetCollection);
for (final tweet t : tweets) System.out.println(t.text);
}
}

关于java - Java中使用Gson解析Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12876786/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com