简体   繁体   中英

How to convert Json string with key-value pair into string with only value

I actually converted my pojo data into json string this way,

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

I got the json string but that is not the format i actually need, i got

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

So, I want to convert Json string with key-value pair as below ,

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

into Json string with only value (without key) as below

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

So I continue after your string 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);

now finalJson is [300,"asd","s",1]

Edit : libraries are as following:

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

Could I ask why do you want to do that? If you retrieve that Json without key-value how you will know, for example, that 300 is his id and not his money property?

You can't difference between your properties and I don't really recommend it.

Anyway, the only way I find to do that, is to "break" your string manually, replacing your properties with blank values, like json.replace("\\"userID\\"", ""); and you should do it for every property.

You could whack the properties of the user into a List<Object> and then JSON that.

This would mean GSON made an JSON array out of the List and you would get what you want.

As this doesn't seem to make much sense as a use case you would have to do a bit of hardcoding - I don't think GSON can do this for you:

final List<Object> props = new LinkedList<>();
props.add(user.getId());
props.add(user.getUserName());
//etc
final String json=gson.toJson(props);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM