当前位置: 首页 > 面试题库 >

Android将JSON对象显示到列表视图

柏明亮
2023-03-14
问题内容

这是我正在处理的代码:

   private final static String SERVICE_URI = "http://restwebservice.com/test/Service.svc";

StringEntity entity;
String var;

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

    callWebService();

    Button btn = (Button) findViewById (R.id.button1);

    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent i = new Intent(MainActivity.this, Test.class);
            startActivity(i);
        }
    });


}

public void callWebService() {

    try {

           // make web service connection
           HttpPost request = new HttpPost(SERVICE_URI + "/TestApplication");
           request.setHeader("Accept", "application/json");
           request.setHeader("Content-type", "application/json");
           // Build JSON string
           JSONStringer TestApp = new JSONStringer().object().key("id")
                        .value("1").key("name").value("manish").key("email")
                        .value("androidhub4you@gmail.com").key("country")
                        .value("india").endObject();
           entity = new StringEntity(TestApp.toString());
           var = EntityUtils.toString(entity);

           Log.d("****Parameter Input****", "Testing:" + TestApp);
           request.setEntity(entity);
           // Send request to WCF service
           DefaultHttpClient httpClient = new DefaultHttpClient();
           HttpResponse response = httpClient.execute(request);

           Log.d("WebInvoke", "Saving: " + response.getStatusLine().toString());
           // Get the status of web service
           BufferedReader rd = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent()));
           // print status in log
           String line = "";
           while ((line = rd.readLine()) != null) {
                 Log.d("****Status Line***", "Webservice: " + line);
           }




    } catch (Exception e) {
           e.printStackTrace();
    }

  }

我想在列表视图上显示它们。您有任何教程可以帮助我入门吗?我是Web服务的新手。谢谢。


问题答案:

列表视图中最受欢迎的教学作品之一,可能会帮助您:

- 拉维的博客

解析json之后要执行的步骤:

 1. Map your json objects to pojo.
 2. Store your pojo in an array list if many are there.
 3. Create a list view with a custom adapter.
 4. update your listview with answer from the pojo's that you have mapped with
    notifyDatasetChanged

您可以使用jackson库用一行代码来解析json。

 //1. Convert Java object to JSON format
 ObjectMapper mapper = new ObjectMapper();
 mapper.writeValue(new File("c:\\user.json"), user);

 //2. Convert JSON to Java object
 ObjectMapper mapper = new ObjectMapper();
 User user = mapper.readValue(new File("c:\\user.json"), User.class);

(单击此链接以获取有关对象映射教程的更多信息)



 类似资料: