0

我实际上以这种方式将我的 pojo 数据转换为 json 字符串,

 Gson gson = new GsonBuilder().disableHtmlEscaping().create();
    String json=gson.toJson(user);

我得到了 json 字符串,但这不是我真正需要的格式,我得到了

json = {"userID":300,"userName":"asd","password":"s","enabled":1}

所以,我想用下面的键值对转换 Json 字符串,

{"userID":300,"userName":"asd","password":"s","enabled":1}

进入只有值(没有键)的 Json 字符串,如下所示

[300,"asd","s",1]
4

3 回答 3

1

所以我在你的字符串之后继续json

// lets deserialize your json string and get a hashmap
Type collectionType = new TypeToken<HashMap<String, Object>>(){}.getType();
HashMap<String, Object> hm = gson.fromJson(json, collectionType);
String finalJson = gson.toJson(hm.values());
// aand taa-daa!!
System.out.println(finalJson);

现在finalJson[300,"asd","s",1]

编辑:库如下:

import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
于 2013-05-14T11:55:23.043 回答
0

我能问一下你为什么要这样做吗?如果您在不key-value知道如何知道的情况下检索该 Json,例如,那300是他的财产id而不是他的money财产?

你不能区分你的属性,我真的不推荐它。

无论如何,我发现这样做的唯一方法是手动“打破”你的字符串,用空白值替换你的属性,就像json.replace("\"userID\"", "");你应该为每个属性都这样做。

于 2013-05-14T11:29:33.347 回答
0

您可以将 的属性user打入 a List<Object>,然后将其打入 JSON 。

这意味着 GSON 用 生成了一个 JSON 数组,List你会得到你想要的。

由于这作为一个用例似乎没有多大意义,因此您必须进行一些硬编码 - 我认为 GSON 无法为您做到这一点:

final List<Object> props = new LinkedList<>();
props.add(user.getId());
props.add(user.getUserName());
//etc
final String json=gson.toJson(props);
于 2013-05-14T11:38:46.853 回答