我想从我的Json数组中检索第一个值到我的android代码中,我正在使用okhttp。这是我的代码
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.textView);
OkHttpClient client = new OkHttpClient();
String url = "http://celebshop.freesite.host/wp-json/wp/v2/pages?fields=slug";
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
final String [] myResponse = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
String [] myJson = myResponse;
String firstObj = myJson[0];
mTextView.setText(firstObj);
}
});
}
}
});
}
}
我在最终的String []上遇到错误。myResponse = response.body()。string();说不舒服的类型需要java.lang.String []找到java.lang.String
这是我想要获取的Json数据
[
{
"slug": "messages"
},
{
"slug": "store"
},
{
"slug": "my-account"
},
{
"slug": "checkout"
},
{
"slug": "cart"
},
{
"slug": "shop"
},
{
"slug": "categories"
},
{
"slug": "home-with-map"
},
{
"slug": "contact"
},
{
"slug": "blog"
}
]
答案 0 :(得分:0)
尝试一下(假设您收到一个JSON数组):
final JSONArray myResponse = new JSONArray(response.body());
这样您就可以遍历您的回复:
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
for ( int i = 0; i < myResponse.length(); i++) {
// Assuming your JSONArray contains JSONObjects
JSONObject entry = myResponse.getJSONObject(i);
}
// Or simply in your case:
mTextView.setText(myResponse.getJSONObject(0));
}
});
答案 1 :(得分:0)
try{
JSONArray myResponse = new JSONArray(response.body());
if(myResponse != null && myResponse.length() > 0){
for (int i = 0; i < myResponse.length(); i++)
JSONObject object = myResponse.getJSONObject(i);
// get your data from jsonobject
mTextView.setText(object.getString(0));
}
}
} catch (JSONException e) {
e.printStackTrace();
}