Парсинг Json файла с помощью Gson

В папке ...\app\src\main\res\raw есть файл test.json:

{
  "qotd_date":"2021-07-22T00:00:00+00:00",
  "quote":
  {
    "id":63363,
    "dialogue":false,
    "private":false,
    "tags":[],
    "url":"https://favqs.com/quotes/meister-eckhart/63363-be-willing-to-",
    "favorites_count":1,
    "upvotes_count":0,
    "downvotes_count":0,
    "author":"Meister Eckhart",
    "author_permalink":"meister-eckhart",
    "body":"Be willing to be a begineer every single morning."
  }
}

Для него я создаю классы:

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("jsonschema2pojo")
public class Example {

    @SerializedName("qotd_date")
    @Expose
    public String qotdDate;
    @SerializedName("quote")
    @Expose
    public Quote quote;

}

И

import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("jsonschema2pojo")
public class Quote {

    @SerializedName("id")
    @Expose
    public Integer id;
    @SerializedName("dialogue")
    @Expose
    public Boolean dialogue;
    @SerializedName("private")
    @Expose
    public Boolean _private;
    @SerializedName("tags")
    @Expose
    public List<Object> tags = null;
    @SerializedName("url")
    @Expose
    public String url;
    @SerializedName("favorites_count")
    @Expose
    public Integer favoritesCount;
    @SerializedName("upvotes_count")
    @Expose
    public Integer upvotesCount;
    @SerializedName("downvotes_count")
    @Expose
    public Integer downvotesCount;
    @SerializedName("author")
    @Expose
    public String author;
    @SerializedName("author_permalink")
    @Expose
    public String authorPermalink;
    @SerializedName("body")
    @Expose
    public String body;
}

Далее начинаю работать с Gson:

import com.google.gson.Gson;

import java.io.FileReader;

public class GsonParser {

    public Example parser() {

        Gson gson = new Gson();

        try(FileReader reader = new FileReader("test.json")) {

            Example example = gson.fromJson(reader, Example.class);

            return example;
        } catch (Exception ex) {

        }
        return null;
    }
}

После чего пробую вывести результат в Log:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GsonParser gsonParser = new GsonParser();
        Example example = gsonParser.parser();

        Log.d("log1",example.toString());

    }
}

Но получаю NullPointerException Подскажите, пожалуйста, как это исправить


Ответы (1 шт):

Автор решения: Vadik

Чтобы считать содержимое файла из raw директории воспользуйтесь методом openRawResource, этот метод на вход принимает идентификатор raw-ресурса:

context.getResources().openRawResource(R.raw.test)

Ваш код тогда будет выглядеть так:

try (InputStreamReader reader = new InputStreamReader(resources.openRawResource(R.raw.test))) {
    return gson.fromJson(reader, Example.class);
} catch (IOException exception) {
    Log.e("GsonParser", "Cannot parse json", exception);
    return null;
}

Никогда не оставляйте блок catch пустым, это затрудняет поиск ошибок!

→ Ссылка