douyi1939 2017-04-25 15:21
浏览 109

如何在1个字符串中分离2个连接的JSONObject? 在Java(Android)

Yes, as question title. I got a single string received in android consist of 2 JSONObject.
I have to do 2 different processes in PHP but both result are returned (echo) in single string result which I don't know how to seperate it.
I'm using :

JSONObject json = new JSONObject(result);
String success = json.optString("success");
// "success" here shows empty in logcat. I think it doesn't get the second json object


Example of Result string:

{"username":"xx","activated":"0"}{"multicast_id":xxx,"success":0,"failure":0,"canonical_ids":0,"results":[{"message_id":"xxx"}]}


How can I do?
(btw 2nd string is Firebase Cloud Messanging result example.
EDIT: I'm using PHP to send FCM, that's why the result is forced to return together with my other string result even I do not (PHP::echo) it)

  • 写回答

2条回答 默认 最新

  • doupu2722 2017-04-25 15:37
    关注

    Use String.split() with proper regex.

    Here is the working code:

        String response = "{\"username\":\"xx\",\"activated\":\"0\"}{\"multicast_id\":xxx,\"success\":0,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"xxx\"}]}";
    
        String[] separated = response.split("\\}\\{");
    
        String str1 = separated[0] + "}";
        String str2 = "{" + separated[1];
    
        Log.d("STRING", "String1: " + str1 + "
    String2: " + str2);
    

    OUTPUT:

    D/STRING: String1: {"username":"xx","activated":"0"}
              String2: {"multicast_id":xxx,"success":0,"failure":0,"canonical_ids":0,"results":[{"message_id":"xxx"}]}
    

    Hope this will help~

    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程