在 ...\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
了 请告诉我如何解决它
要从目录中读取文件的内容
raw
,请使用openRawResource方法,该方法接受原始资源标识符作为输入:您的代码将如下所示:
永远不要将块
catch
留空,这样会更难发现错误!