Java 发出结构化JSON请求

Java 发出结构化JSON请求,java,android,json,Java,Android,Json,我在使用我的应用程序与后端通信时遇到问题。我试图创建一个JSON请求,将用户名和密码值传递给服务器。服务器接受这些值,并假定返回我映射到用户对象的用户 现在,服务器已经设置好,以便返回与设置为接收的JSON完全相同的JSON 我正在使用Jackson进行所有的JSON映射,有没有办法更改我传递的JSON以匹配下面的JSON 这是我正在发送的JSON [ { "name":"username", "value":"hi" }, {

我在使用我的应用程序与后端通信时遇到问题。我试图创建一个JSON请求,将用户名和密码值传递给服务器。服务器接受这些值,并假定返回我映射到用户对象的用户

现在,服务器已经设置好,以便返回与设置为接收的JSON完全相同的JSON

我正在使用Jackson进行所有的JSON映射,有没有办法更改我传递的JSON以匹配下面的JSON

这是我正在发送的JSON

[  
   {  
      "name":"username",
      "value":"hi"
   },
   {  
      "name":"password",
      "value":"hi"
   }
]
以下是服务器接收JSON时的样子

{  
   "password":"hi",
   "username":"hi"
}
这是我的用户休息时间

    public static class AuthUser extends
            AsyncTask<ArrayList<NameValuePair>, Void, User> {

        public interface AuthUserDelegate {

            public void getAuthenticatedUser(User user) throws JSONException;
        }

        AuthUserDelegate delegate;
        Context mContext;

        public AuthUser(Context context) {

            mContext = context;
            this.delegate = (AuthUserDelegate) context;
        }

        @Override
        protected User doInBackground(ArrayList<NameValuePair>... params) {
            ObjectMapper mapper = new ObjectMapper(); // create once, reuse
            User user = null;
            String url = ROUTE_USER_AUTH;
            HttpPost httppost = new HttpPost(url);
            HttpClient httpclient = new DefaultHttpClient();
            String UserJSONResponse = null;

            try {

                String jsonString = mapper.writeValueAsString(params[0]);
                StringEntity m_stringEntity = new StringEntity(jsonString);


//              UrlEncodedFormEntity m_entity = new UrlEncodedFormEntity(
//                      params[0]);
                httppost.setEntity(m_stringEntity);
                httppost.addHeader("Content-type", "application/json");

                HttpResponse postResponse = httpclient.execute(httppost);

                UserJSONResponse = EntityUtils.toString(postResponse
                        .getEntity());
                user = mapper.readValue(UserJSONResponse, User.class);

                Log.e("E  AUTH USER", "Status code: "
                        + postResponse.getStatusLine().getStatusCode());

                Log.e("E  AUTH USER", "Auth was sent, Server returned: \n"
                        + UserJSONResponse);

            } catch (JsonProcessingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                httppost.abort();
                Log.e("E IO EXCEPTION", "Error for URL: " + url, e);
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return user;
        }

        @Override
        protected void onPostExecute(User result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            // User user = new User();
            // Log.e("AUTH POST USERNAME", result.getUser_name());
            try {
                delegate.getAuthenticatedUser(result);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
公共静态类AuthUser扩展
异步任务{
公共接口AuthUserDelegate{
public void getAuthenticatedUser(用户用户)抛出JSONException;
}
授权用户代表;
语境;
公共AuthUser(上下文){
mContext=上下文;
this.delegate=(AuthUserDelegate)上下文;
}
@凌驾
受保护的用户doInBackground(ArrayList…params){
ObjectMapper mapper=new ObjectMapper();//创建一次,重用
User=null;
字符串url=ROUTE\u USER\u AUTH;
HttpPost HttpPost=新的HttpPost(url);
HttpClient HttpClient=新的DefaultHttpClient();
字符串UserJSONResponse=null;
试一试{
字符串jsonString=mapper.writeValueAsString(参数[0]);
StringEntity m_StringEntity=新的StringEntity(jsonString);
//UrlEncodedFormEntity m_entity=新的UrlEncodedFormEntity(
//参数[0]);
httppost.setEntity(m_stringEntity);
addHeader(“内容类型”、“应用程序/json”);
HttpResponse postResponse=httpclient.execute(httppost);
UserJSONResponse=EntityUtils.toString(postResponse
.getEntity());
user=mapper.readValue(UserJSONResponse,user.class);
Log.e(“e身份验证用户”,“状态代码:”
+postResponse.getStatusLine().getStatusCode());
Log.e(“e AUTH USER”,“已发送验证,服务器返回:\n”
+用户JSONResponse);
}捕获(JsonProcessingException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(不支持的编码异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
httppost.abort();
Log.e(“IO异常”,“URL错误:”+URL,e);
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回用户;
}
@凌驾
受保护的void onPostExecute(用户结果){
//TODO自动生成的方法存根
super.onPostExecute(结果);
//用户=新用户();
//Log.e(“AUTH POST USERNAME”,result.getUser_name());
试一试{
delegate.getAuthenticatedUser(结果);
}捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
}
收集信息和执行异步任务的主要活动

    @Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.btnSignIn:
        username = etUsername.getText().toString().trim();
        password = etPassword.getText().toString().trim();

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("username", username));
        nameValuePairs.add(new BasicNameValuePair("password", password));
        new UserREST.AuthUser(this).execute(nameValuePairs);

        break;

    default:
        break;
    }

}
@覆盖
公共void onClick(视图v){
//TODO自动生成的方法存根
开关(v.getId()){
案例R.id.btnSignIn:
username=etUsername.getText().toString().trim();
password=etPassword.getText().toString().trim();
ArrayList nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“用户名”,username));
添加(新的BasicNameValuePair(“密码”,password));
新建UserREST.AuthUser(this.execute)(nameValuePairs);
打破
违约:
打破
}
}

定义您自己的JSONObject:

JSONObject input = new JSONObject();
input.put("username", "hi");
input.put("password", "hi");
然后像这样执行您的任务:

new UserREST.AuthUser(this).execute(input);
public static class AuthUser extends AsyncTask<JSONObject, Void, User>
{
    // [...]

    @Override
    protected User doInBackground(JSONObject... params)
    {
        User user = null;
        String url = ROUTE_USER_AUTH;
        HttpPost httppost = new HttpPost(url);
        HttpClient httpclient = new DefaultHttpClient();
        String UserJSONResponse = null;

        try
        {
            StringEntity m_stringEntity = new StringEntity(params[0].toString());
            // [...]
任务应如下所示:

new UserREST.AuthUser(this).execute(input);
public static class AuthUser extends AsyncTask<JSONObject, Void, User>
{
    // [...]

    @Override
    protected User doInBackground(JSONObject... params)
    {
        User user = null;
        String url = ROUTE_USER_AUTH;
        HttpPost httppost = new HttpPost(url);
        HttpClient httpclient = new DefaultHttpClient();
        String UserJSONResponse = null;

        try
        {
            StringEntity m_stringEntity = new StringEntity(params[0].toString());
            // [...]
公共静态类AuthUser扩展异步任务
{
// [...]
@凌驾
受保护的用户doInBackground(JSONObject…参数)
{
User=null;
字符串url=ROUTE\u USER\u AUTH;
HttpPost HttpPost=新的HttpPost(url);
HttpClient HttpClient=新的DefaultHttpClient();
字符串UserJSONResponse=null;
尝试
{
StringEntity m_StringEntity=新的StringEntity(参数[0].toString());
// [...]

使用JSONObject而不是使用NameValuePair

public String getJSONAuth(String user, String pass) {
    JSONObject jo = new JSONObject();
    jo.putString("username", user);
    jo.putString("password", pass);
    return jo.toString();
}
这将返回您要查找的内容