使用GSON将HashMap映射到JSON [英] hashmap to JSON using GSON

查看:100
本文介绍了使用GSON将HashMap映射到JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Gson将我的Java对象转换为GSON。我想将我的HashMap转换为JSON。



假设我的Object1具有结构:

  public class Object1 {
String a;
字符串b;
字符串c;

字符串toString(){
返回a:+ a +b:+ b +c:+ c;
}
}

和我的Object2有结构:

  public class Object2 {
String e;
String f;
}

我希望我的最终JSON看起来像

  {
{
a:aValue,
b:bValue,
c:cValue
}:{
e:eValue,
f:fValue
}
}

我把它当作

  {
a:aValue b:bValue c:cValue:{
e:eValue,
f:fValue
}
}

是否有可能以期望的形式存在。



我尝试使用JSON文档中给出的TypeToken。这没有帮助。

解决方案

您无法获得预期的表单。



JSON的元素始终是键值paar ,并且键始终是文本(或字符串)。但在你的情况下,键是一个对象。

根据我的理解,如果你想把键作为一个Object来使用,你可以把它作为一个String来使用,然后使用ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)将其转换为您期望的类。

  final ObjectMapper mapper = new ObjectMapper (); 
Object1 object1 = mapper.readValue(object1String,Object1.class)


I am using Gson for converting my Java Objects to GSON. I wanted to convert my HashMap to JSON.

Assuming my Object1 has structure:

public class Object1 {
     String a;
     String b;
     String c;

     String toString() {
          return "a: " + a + " b: " + b + " c: " + c;
     }
}

and my Object2 has Structure:

public class Object2 {
    String e;
    String f;
}

I wanted my final JSON to look like

{
    {
      "a" : "aValue",
      "b" : "bValue",
      "c" : "cValue"
    } : {
           "e" : "eValue",
           "f" : "fValue"
         } 
}

Bit I am getting it as

{
 "a: aValue b: bValue c: cValue" : {
        "e" : "eValue",
        "f" : "fValue"
  }
}

Is this possible to have it in desired form.

I tried using TypeToken given in JSON documentation. That didn't help.

解决方案

You cannot get your expected form.

JSON's element is always a key-value paar and the key is always a text (or String). But in your case the key is an object.

From my understanding, if you wanna to consume the key as an Object, you could get it as a String and then use ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper) to convert it to your expected class.

final ObjectMapper mapper = new ObjectMapper();
Object1 object1 = mapper.readValue(object1String, Object1.class)

这篇关于使用GSON将HashMap映射到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆