如何在android中使用GSON解析json解析
Posted
技术标签:
【中文标题】如何在android中使用GSON解析json解析【英文标题】:How to parse json parsing Using GSON in android 【发布时间】:2014-05-10 07:52:55 【问题描述】:我正在使用GSON
来解析 Json 数据。我的 Json 数据如下:
"count": "12",
"colbreak": 1,
"name": "unary rels",
"score": "9090",
"Words": [
"count": 6,
"word": "prp_għaċ-",
"name": "prp_għaċ-",
"score": 9.1,
"Words": "kol",
"seek": 2231297
],
"seek": 0
GsonParse.java
public class GsonParse
@SerializedName("count")
public String count;
@SerializedName("colbreak")
public String colbreak;
@SerializedName("name")
public String count;
@SerializedName("score")
public String score;
@SerializedName("Words")
public List<Words> mWords = new ArrayList<Words>();
@SerializedName("seek")
public String seek;
我正在使用下面的方法来解析这个 JSON 数据。
public static <T> ArrayList<T> JsonParse(T t, String response)
// convert String into InputStream
InputStream in = new ByteArrayInputStream(response.getBytes());
JsonReader reader;
ArrayList<T> lcs = new ArrayList<T>();
try
reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
Gson gson = new Gson();
reader.beginObject();
while (reader.hasNext())
T cse = (T) gson.fromJson(reader, t.getClass());
lcs.add(cse);
reader.endObject();
/*
* reader.nextName(); reader.nextString(); reader.nextName();
* reader.nextString();
*/
reader.close();
catch (UnsupportedEncodingException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
return (ArrayList<T>) lcs;
我面临以下错误。
03-31 10:14:26.968: E/androidRuntime(18578): com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NAME at line 1 column 73
【问题讨论】:
请发布错误日志。 请同时发布Words
class。
@Sid 如何解析这个 json 字符串?
【参考方案1】:
您可以尝试像这样读取 gson 值:
try
AssetManager assetManager = getAssets();
InputStream ims = assetManager.open("file.txt");
Gson gson = new Gson();
Reader reader = new InputStreamReader(ims);
GsonParse gsonObj = gson.fromJson(reader, GsonParse.class);
catch(IOException e)
e.printStackTrace();
假设您只是收到这一块而不是列表。而且这些数据当前位于 assets 文件夹中的一个文件中。您可以将其更改为要从中读取的流。
你使用的类应该是这样的:
GsonParse.class
public class GsonParse
@SerializedName("count")
private String count;
@SerializedName("colbreak")
private String colbreak;
@SerializedName("name")
private String name;
@SerializedName("score")
private String score;
@SerializedName("Words")
private List<Words> mWords = new ArrayList<Words>();
@SerializedName("seek")
private String seek;
public String getCount()
return count;
public void setCount(String count)
this.count = count;
public String getColbreak()
return colbreak;
public void setColbreak(String colbreak)
this.colbreak = colbreak;
private String getName()
return name;
private void setName(String name)
this.name = name;
public String getScore()
return score;
public void setScore(String score)
this.score = score;
public List<Words> getmWords()
return mWords;
public void setmWords(List<Words> mWords)
this.mWords = mWords;
public String getSeek()
return seek;
public void setSeek(String seek)
this.seek = seek;
Words.class
public class Words
@SerializedName(value ="count")
private String count;
@SerializedName(value="word")
private String word;
@SerializedName(value="score")
private String name;
@SerializedName(value="Words")
private String words;
@SerializedName(value="seek")
private String seek;
public String getCount()
return count;
public void setCount(String count)
this.count = count;
public String getWord()
return word;
public void setWord(String word)
this.word = word;
public String getName()
return name;
public void setName(String name)
this.name = name;
public String getWords()
return words;
public void setWords(String words)
this.words = words;
public String getSeek()
return seek;
public void setSeek(String seek)
this.seek = seek;
words.class中缺少一个参数,你可以添加它。
GSON 不直接支持 UTF-8 字符。所以当使用 http 接收响应时,您必须在 http 本身的响应中将其转换为 utf-8 格式。
您可以尝试使用:
String jsonString = new Gson().toJson(objectToEncode);
byte[] utf8JsonString = jsonString.getBytes("UTF8");
responseToClient.write(utf8JsonString, 0, utf8JsonString.Length);
【讨论】:
Gson 不使用 get/swt 为什么要制作它们?至少如果你想添加 get/set 使字段私有 @MarcoAcierno 是的 gson 不使用它们,只是为了获取数据:).. 正确它们应该是私有的。我简单地选择了用户的类 :).. 我改变了.. :)【参考方案2】:你好使用下面的 gradle lib
compile 'com.google.code.gson:gson:2.2.4'
Json 类
import java.util.List;
public class GsonParse
/**
* count : 12
* colbreak : 1
* name : unary rels
* score : 9090
* Words : ["count":6,"word":"prp_għaċ-","name":"prp_għaċ-","score":9.1,"Words":"kol","seek":2231297]
* seek : 0
*/
private String count;
private int colbreak;
private String name;
private String score;
private int seek;
/**
* count : 6
* word : prp_għaċ-
* name : prp_għaċ-
* score : 9.1
* Words : kol
* seek : 2231297
*/
private List<WordsBean> Words;
public String getCount()
return count;
public void setCount(String count)
this.count = count;
public int getColbreak()
return colbreak;
public void setColbreak(int colbreak)
this.colbreak = colbreak;
public String getName()
return name;
public void setName(String name)
this.name = name;
public String getScore()
return score;
public void setScore(String score)
this.score = score;
public int getSeek()
return seek;
public void setSeek(int seek)
this.seek = seek;
public List<WordsBean> getWords()
return Words;
public void setWords(List<WordsBean> Words)
this.Words = Words;
public static class WordsBean
private int count;
private String word;
private String name;
private double score;
private String Words;
private int seek;
public int getCount()
return count;
public void setCount(int count)
this.count = count;
public String getWord()
return word;
public void setWord(String word)
this.word = word;
public String getName()
return name;
public void setName(String name)
this.name = name;
public double getScore()
return score;
public void setScore(double score)
this.score = score;
public String getWords()
return Words;
public void setWords(String Words)
this.Words = Words;
public int getSeek()
return seek;
public void setSeek(int seek)
this.seek = seek;
调用 API 将响应放入下面的代码并检索数据
GsonParse gsonparse = gson.fromJson(response, GsonParse.class);
//gsonparse.getWords() // It will returns list of Words
//Also do loop and get more data using data
gsonparse.getColbreak();
gsonparse.getSeek();
for (GsonParse.WordsBean data:gsonparse.getWords())
data.getName();
希望对你有所帮助..
【讨论】:
在获取数据时给出警告【参考方案3】:替换
@SerializedName("name")
public String count;
与
@SerializedName("name")
public String name;
我想问题是您同时使用 public String count;
和 @SerializedName("count")
和 @SerializedName("name")
谢谢。
【讨论】:
这让我很吃惊,但是为什么用户没有收到一个编译时错误,说明计数已经定义?【参考方案4】:试试这个:
JSONArray jsonarray = jsonObject.getJSONArray("responseData");
Type listType = new TypeToken<ArrayList<AllUsers>>().getType();
List<AllUsers> allUserses =
new GsonBuilder().create().fromJson(jsonarray.toString(), listType);
for(AllUsers user: allUserses)
allUsersDao.insertOrReplace(user);
【讨论】:
尝试格式化你的代码,我猜一些解释不会造成任何伤害。【参考方案5】:您的代码中缺少很多东西..
请查看下面的代码并尝试此代码..
import java.util.List;
public class GsonParse
public GsonParse()
public String count = "";
public String colbreak = "";
public String name = "";
public String score = "";
public int seek = 0;
List<WordsData> Words;
public String getCount()
return count;
public void setCount(String count)
this.count = count;
public String getColbreak()
return colbreak;
public void setColbreak(String colbreak)
this.colbreak = colbreak;
public String getName()
return name;
public void setName(String name)
this.name = name;
public String getScore()
return score;
public void setScore(String score)
this.score = score;
public int getSeek()
return seek;
public void setSeek(int seek)
this.seek = seek;
public List<WordsData> getWords()
return Words;
public void setWords(List<WordsData> words)
Words = words;
public class WordsData
public WordsData()
public int count = 0;
public String word = "";
public String name = "";
public double score = 0.0;
public String Words = "";
public int seek = 0;
public int getCount()
return count;
public void setCount(int count)
this.count = count;
public String getWord()
return word;
public void setWord(String word)
this.word = word;
public String getName()
return name;
public void setName(String name)
this.name = name;
public double getScore()
return score;
public void setScore(double score)
this.score = score;
public String getWords()
return Words;
public void setWords(String words)
Words = words;
public int getSeek()
return seek;
public void setSeek(int seek)
this.seek = seek;
更多详情请看example
【讨论】:
@dipali,如果 JSON 字段名称与您的实例变量名称不同,您只需要使用“@serializedName”。当字段名称与实例变量名称完全匹配时,gson 足够聪明。以上是关于如何在android中使用GSON解析json解析的主要内容,如果未能解决你的问题,请参考以下文章
如何在 android 中解析来自 url 或 restful 服务的大量 JSON 数据?没有 GSON
一起Talk Android吧(第三百五十三回:Gson库解析JSON数组一)