【问题标题】:Android gson serialization issueAndroid gson 序列化问题
【发布时间】:2013-05-11 01:07:16
【问题描述】:

我的 Android 应用程序向我的 .NET Web Api 发出 HttpPost 请求。

我正在使用 json 数据类型和 gson 类来序列化我的对象。

这是我关于序列化的代码:

    HttpPost post = new HttpPost();
    post.setURI(new URI("my url goes here"));
    HashMap<String, String> hashMap = new HashMap<String, String>();
    hashMap.put("username", username);
    hashMap.put("userCredentials", new Gson().toJson(credentials, UCredentials.class));
    // username and credentials are parameters.
    post.setHeader("Content-Type", "application/json; charset=utf-8");
    post.setEntity(new StringEntity(new Gson().toJson(hashMap)));

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

除了hashMap.put("userCredentials", new Gson().toJson(credentials, UCredentials.class)); 代码行,一切正常。但是有了这条线......

Gson 类给我的 json 为:

{
    "userCredentials":
        "{
            \"emailOrUsername\":\"asd@sadas.com\",
            \"password\":\"113\"
         }",
    "username":"sdggfsdgf"
}

它不是有效的 json 模式。我需要像这样的 json 输出:

{
        "userCredentials":
            {
                "emailOrUsername":"asd@sadas.com",
                "password":"113"
            },
        "username":"sdggfsdgf"
}

我应该怎么做才能做到这一点?

提前致谢。

【问题讨论】:

    标签: android http-post gson


    【解决方案1】:

    您的第一个问题在这里:

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

    进入 HashMap 的是一个可解析 JSON 的字符串。当您跟进时:

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

    那个字符串被转义了,因为它不是一个对象。

    你真正想做的是这样的:

    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.
    }
    

    这应该做你想做的,但是既然你说它不起作用....

    我不确定 UCredentials 类。它似乎是您自己的代码。这是我的猜测:

    public class UCredentials {
    
        public String emailOrUsername;
    
        public String password;
    
    }
    

    这里是简化的代码:

    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));
        }
    
    }
    

    这是输出:

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

    如果您可以发布您的错误消息,我会尝试帮助调试。

    【讨论】:

    • 首先必须是"HashMap hashMap = new HashMap();"不是 "HashMap hashMap = new HashMap();"
    • 而且代码不起作用。 hashMap.put("userCredentials", 凭据);行没有对序列化做任何事情。
    • 尝试阅读有关泛型的文档。 sites.google.com/site/gson/…
    • 我已经添加了 TypeToken 声明。
    • 抱歉延迟回答。我以前试过这个。我最后一次尝试了 onCreate() 方法。有效。问题是我是 C# 开发人员,我对 C# 和 Java 编程感到困惑。我有一些不正确的定义。很抱歉造成混乱。非常感谢您的回答。
    【解决方案2】:

    如果你使用 gson 来序列化你的对象,你需要使用 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;
    

    对不起我的英语。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      相关资源
      最近更新 更多