Strange “nameValuePairs” key appear when using Gson

前端 未结 5 1349
我寻月下人不归
我寻月下人不归 2021-02-12 10:17

I am trying to rebuild an Object from its fields( i get the fields as a JSONObject), something like this:

JSONObject jObj = new JSONObject();  

JSO         


        
5条回答
  •  北荒
    北荒 (楼主)
    2021-02-12 10:57

    I had the same problem when I wanted to use Gson only for pretty print. JsonObject is working fine but if you still want to use JSONObject instead of JsonObject then you can use it that way:

    public class JsonUtil {
        public static String toPrettyFormat(String jsonString)
        {
            JsonParser parser = new JsonParser();
            JsonObject json = parser.parse(jsonString).getAsJsonObject();
    
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String prettyJson = gson.toJson(json);
    
            return prettyJson;
        }
    }
    

    and simply pass JSONObject as string like this:

    String prettyJson = JsonUtil.toPrettyFormat(jsonObject.toString());
    

提交回复
热议问题