0

I'm trying to parse the following url:

http://api.crossref.org/works?rows=2

When I parse it through Gson, I got some records but somehow some others stay null.

Here is my code:

    BufferedReader in = new BufferedReader(new InputStreamReader(url_tdm.openStream(), "UTF-8"));
    StringBuffer buffer = new StringBuffer();

    int read;
    char[] chars = new char[1024];
    while ((read = in.read(chars)) != -1)
    buffer.append(chars, 0, read); 

    String jsonLine = buffer.toString();

    JsonReader reader = new JsonReader(new StringReader(jsonLine));
    reader.setLenient(true);  // this is for Malformed json

    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES).create();

    Crossref answer = gson.fromJson(reader, Crossref.class );

    List<Items> ao = answer.message.items;

    public class Crossref {
    public Message message;}

    public class Message {
    public List<Items> items;}

    public class Items {   
    public List<String> containerTitle;
    public List<String> ISSN;
    public String publisher;
    public List<String> title;
    public String DOI;
    public String type;}

So as a result of my code above, I can get container-title, publisher and title values. But ISSN and DOIs are null.

I used a FieldNamingPolicy because "container-title" contains a dash and I could not name my field like that in java (so I wrote it as camel case containerTitle).

I am not sure if this affects DOI and ISSN records which are upper case or is it something totally different?

Deividi Cavarzan
  • 10,034
  • 13
  • 66
  • 80
mlee_jordan
  • 772
  • 4
  • 18
  • 50
  • 1
    Tried generating a schema at http://www.jsonschema2pojo.org ? – Evan Knowles Jan 08 '15 at 15:04
  • Thanks @EvanKnowles. By applying first http://jsonschema.net/#/ and after getting schema I used jsonschema2pojo.org and I could run the suggested code. However, i am still curios what was the problem in my code. – mlee_jordan Jan 08 '15 at 16:44

1 Answers1

0

The best way to fix something like this is to use a gson custom deserializer

I suggest that you read this other question to see a good exemple: How do I write a custom JSON deserializer for Gson?

And you can find some other greats exemples and explanations here

Community
  • 1
  • 1
Thermech
  • 4,371
  • 2
  • 39
  • 60