【问题标题】:How to convert the jsonObject to element in android如何将jsonObject转换为android中的元素
【发布时间】:2021-05-13 00:02:53
【问题描述】:

我的对象就像下面的 json。我需要将对象转换为 json 元素。但它像字符串一样转换。我该如何转换?

我的对象:

{"data":"valuse","one_data":{"user_id":"id","name":"name"}}

返回如下:

{"response":"{\"data\":\"valuse\",\"one_data\":{\"user_id\":\"id\",\"name\":\"name\"}}"}

预期:

{"response": {"data":"valuse","one_data":{"user_id":"id","name":"name"}}}

我的代码:

JSONObject myData = jsdata1;
Gson gson = new Gson();
JsonElement element = gson.fromJson(myData.toString(), JsonElement.class);
System.out.println("element === " + element);

【问题讨论】:

    标签: java android json gson


    【解决方案1】:

    **您可以使用 Pretty Print JSON 输出 (Jackson)。

    下面是一些例子**

    1.转换对象并以JSON格式打印其输出。`

     User user = new User();
     //...set user data
     ObjectMapper mapper = new ObjectMapper();
     System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));`
    

    2.Pretty Print JSON 字符串

     String test = "{\"age\":29,\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"],\"name\":\"myname\"}";
    Object json = mapper.readValue(test, Object.class);    
         System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
    

    参考:http://www.mkyong.com/java/how-to-enable-pretty-print-json-output-jackson/

    【讨论】:

    • 你能解释一下为什么 gson 或 stringbuilder 不适合我吗?
    • 能否导入这两个包,然后检查import com.google.gson.Gson;导入 com.google.gson.GsonBuilder;
    • 我的代码是这样的。仍然在android中出现错误。 JSONObject 工作 = 新 JSONObject(); JSONObject 内容 = 新 JSONObject(); content.put("数据", 数据); // data = value content.put("data1", data1); data1 = {"value1":"value22", "value": val11"} joob.put("response", content);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 2016-12-21
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    相关资源
    最近更新 更多