Android App with ASP.NET WebAPi Server - send comp

2019-07-13 20:13发布

I have a Android App which is via Web Services connected with my ASP.NET WebApi Server. For sending requests I am using AsyncHttpClient and for passing parameters to the server I use RequestParams. Now I want to send a complex object that contains a list with other complex objects to my server, and there is the issue. How am I supposed to do that? For simple types, it is pretty easy, since I just need to call parameter.add("paramname", paramvalue); multiple times on the same parameter name, and on the server side I receive a list. But what should the call look like when my list has complex types so that I receive a list on my server containing these complex types?

Let's say I have a book that contains a list of authors:

class Book {
   string title;
   int year;
   List<Authors> authors;
}

class Author {
    string name;
    int    age;
}

How should I pass a Book (including authors)to my server using Request params (let's assume the data class on the server looks the same)?

I've almost forgot that the server accepts JSON as format.

Thanks

1条回答
淡お忘
2楼-- · 2019-07-13 20:40
  1. First you need to declare the Book and Author (POJO) in your android project.
  2. Then you need to convert your complex objects to json object (you can either do it manually or with GSON Libary)

    Gson gson = new Gson();
    String jsonString = gson.toJson(myBook);
    JSONObject bookJsonObj = new JSONObject();
    
    try {
        bookJsonObj = new JSONObject(jsonString);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    
  3. Then you can use library like Google Volley to post your request to server:

    JsonObjectRequest myJsonRequest = new JsonObjectRequest(Request.Method.POST,
                    ACTION_METHOD_URL, bookJsonObj , new Response.Listener<JSONObject>() {
    
        @Override
        public void onResponse(JSONObject jObj) {
    
        }
    }, new Response.ErrorListener() {
    
        @Override
        public void onErrorResponse(VolleyError error) {
    
        }
    });
    volleySingleton.addToRequestQueue(myJsonRequest, MY_REQUEST_TAG);
    
  4. Finally add Action method for the request in your api controller

    public IHttpActionResult YourActionMethod(Book book)    
    {
        // do your request action here
    }
    

EDIT: for posting JSON via AsyncHttpClient use this:

    StringEntity entity = new StringEntity(bookJsonObj.toString());
    client.post(context, ACTION_METHOD_URL, entity, "application/json",
            responseHandler)
查看更多
登录 后发表回答