[英]How to handle nested json objects/arrays in android using retrofit and gson?
This is my json object structure: 这是我的json对象结构:
object {1}
products [3]
0 {14}
1 {14}
2 {14}
and here is my code: 这是我的代码:
gitapi.java gitapi.java
public interface gitapi {
@GET("/admin/API/{user}")
public void getFeed(@Path("user") String user, Callback<gitmodel> response);
}
MainActivity.java MainActivity.java
Button click;
TextView tv;
EditText edit_user;
ProgressBar pbar;
String API = "http://xxyyzz.com"; //BASE URL
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click = (Button) findViewById(R.id.button);
tv = (TextView) findViewById(R.id.tv);
edit_user = (EditText) findViewById(R.id.edit);
pbar = (ProgressBar) findViewById(R.id.pb);
pbar.setVisibility(View.INVISIBLE);
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String user = edit_user.getText().toString();
pbar.setVisibility(View.VISIBLE);
//Retrofit section start from here...
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API).build(); //create an adapter for retrofit with base url
gitapi git = restAdapter.create(gitapi.class); //creating a service for adapter with our GET class
//Now ,we need to call for response
//Retrofit using gson for JSON-POJO conversion
git.getFeed(user, new Callback<gitmodel>() {
@Override
public void success(gitmodel gitmodel, Response response) {
//we get json object from github server to our POJO or model class
tv.setText("getTitle :" + gitmodel.getTitle());
pbar.setVisibility(View.INVISIBLE); //disable progressbar
}
@Override
public void failure(RetrofitError error) {
tv.setText(error.getMessage());
pbar.setVisibility(View.INVISIBLE); //disable progressbar
}
});
}
});
}
The problem is I dont know how to access the inner json objects. 问题是我不知道如何访问内部json对象。 Is there a way to do this. 有没有办法做到这一点。
from jsonschemaa2pojo.com i got the pojo file as 2 files one for gitmodel.java and other for product.java. 从jsonschemaa2pojo.com我得到的pojo文件是2个文件,一个是gitmodel.java,另一个是product.java。 My Question is how can i access the objects within the json object. 我的问题是如何访问json对象中的对象。
Ex: you can see the tv.setText("getTitle :" + gitmodel.getTitle()); 例如:您可以看到tv.setText(“ getTitle:” + gitmodel.getTitle()); in MainActivity.java which is what i want to achieve. 在MainActivity.java中,这是我想要实现的。 i want to call the methods in order to access the inner object. 我想调用方法以访问内部对象。 Thank you... 谢谢...
You have to create POJO using this link : http://www.jsonschema2pojo.org/ 您必须使用以下链接创建POJO: http : //www.jsonschema2pojo.org/
In this link select Source type: JSON and Annotation style: GSON and after that click on preview it will create pojo as per your Json and you will easily parse json. 在此链接中,选择源类型:JSON和注释样式:GSON ,然后单击预览 ,它将根据您的Json创建pojo,您将轻松解析json。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.