Android gson serialization issue

杀马特。学长 韩版系。学妹 提交于 2019-12-05 22:53:09

Your first issue is here:

 hashMap.put("userCredentials", new Gson().toJson(credentials, UCredentials.class)); 

What is going into the HashMap is a String that is JSON parsable. When you follow that up with:

post.setEntity(new StringEntity(new Gson().toJson(hashMap)));

That string gets escaped since it is not an object.

What you really want to do is something like this:

HttpPost post = new HttpPost();

post.setURI(new URI("my url goes here"));
// Here we say that the Hashmap takes Object as its value.
HashMap<String, String> hashMap = new HashMap<String, Object>();
hashMap.put("username", username);
// Here we put the credentials object in the HashMap
hashMap.put("userCredentials", credentials);
// username and credentials are parameters.
post.setHeader("Content-Type", "application/json; charset=utf-8");
Type mapType = new TypeToken<HashMap<String, Object>>() {}.getType();
post.setEntity(new StringEntity(new Gson().toJson(hashMap, mapType)));

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(post);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
    // If successful.
}

This should do what you want, but since you say it doesn't work....

I'm not sure about the UCredentials class. It appears to be your own code. Here's a guess on my part:

public class UCredentials {

    public String emailOrUsername;

    public String password;

}

Here is simplified code:

import java.lang.reflect.Type;
import java.util.HashMap;
import com.google.gson.Gson;    
import com.google.gson.reflect.TypeToken;


public class Test {

    public static void main(String[] args) {

        Gson gson = new Gson();
        HashMap<String, Object> hashMap = new HashMap<String, Object>();

        UCredentials uc = new UCredentials();
        uc.emailOrUsername = "me@somehost.com";
        uc.password = "pAsSwOrD";

        hashMap.put("username", "ME");
        hashMap.put("userCredentials", uc);

        Type mapType = new TypeToken<HashMap<String, Object>>() {}.getType();
        System.out.println(gson.toJson(hashMap, mapType));
    }

}

And this is the output:

{"userCredentials":{"emailOrUsername":"me@somehost.com","password":"pAsSwOrD"},"username":"ME"}

If you can post your error message, I'll try and help debug.

If do you using gson to serilizable your object, you need using the URLEncoder.encode(yourClass, "UTF-8");

  Gson gson = new Gson();
  String objectSerializable;

  objectSerializable= gson.toJson(yourObject, yourClass.class).toString();

  pedidoSerializado = URLEncoder.encode(objectSerializable, "UTF-8");
  String urlPathService = "http://xxx.xxx.xxx/RestfulAPI/api?object="+objectSerializable;

Sorry for my english.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!