开发者

Parsing Gson with Json not working for Android

开发者 https://www.devze.com 2023-03-13 18:14 出处:网络
I have a web service class that successfully pulls my JSON from a feed into a String.I want to use Gson to parse it into a List of a custom class, but the parsing messes up somehow.

I have a web service class that successfully pulls my JSON from a feed into a String. I want to use Gson to parse it into a List of a custom class, but the parsing messes up somehow.

Right now the code that does the parsing looks like this: http://pastie.org/2079115. The JSON is included.

I believe the issue occurs because of that extra layer of

"article": { ... }, "article": { ... } ...

Pretty much everything I can find online tells me to do it like the above, including the Gson API.

The issue is that the articles variable ends up as a list with the correct number of Articles, but all of the data in each Article is null. I've toyed with the structure of

Type collectionType = new TypeToken<ArrayList<Article>>(){}.getType;
开发者_Go百科

but any changes just ends up in the articles variable being null and not even holding null Articles. Any idea where to go from here?

For reference, my Article.java looks like this: http://pastie.org/2079165


The problem is that JSON structure does not match the Java structure attempting to be deserialized into, and no custom deserialization processing to handle the mismatch is provided. So, yes, "the issue occurs because of that extra layer".

A simple solution would be to change the Java structure to match the JSON structure. The JSON structure is

an array of 
    an unnamed object with 
        one element named article with value of
            an object with 
                seven elements named author_id, body, catagory, created_at, id, published, updated_at

Here is such an example, using the same JSON as in the original question.

import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Type collectionType = new TypeToken<ArrayList<ArticleContainer>>() {}.getType();
    ArrayList<ArticleContainer> articles = gson.fromJson(new FileReader("input.json"), collectionType);
    System.out.println(gson.toJson(articles));
  }
}

class ArticleContainer
{
  Article article;
}

class Article
{
  public int author_id;
  public String body;
  public String catagory;
  public String created_at;
  public int id;
  public String published;
  public String updated_at;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号