有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将带空格的字符串转换为json

我有问题的文本,我得到它作为服务器响应。我想把它写进共享偏好。但它抛出异常,因为有空格和一些值为空的键

Name=alik,picture=,

    String jsonStr="{IsEmailSubscription=true, Name=Ali K,picture=, 
Id=2534, Surname=Murat, Email=Email}";

    JSONObject obj = new JSONObject(jsonStr);
    settings.edit().putString(SharedText.Customer.toString(),obj.toString()).commit();

你有什么建议

编辑1:

  org.json.JSONException: Unterminated object at character 39 of 

{IsEmailSubscription=true, Name=Ahmet k, Id=2534, Surname=Kosen, 

MobilePhone=5363481189, Email=Email}

服务器返回字符串,但我需要将其转换为 JSON,为此我使用JSONObject


共 (1) 个答案

  1. # 1 楼答案

    在定义两个问题时:

    1. 您的JSON格式与其他人指出的不正确
    2. 为了从JSON对象获取可选字段,可以使用JSONObject中存在的optIntoptString类API。 json字符串的正确格式应为:

      String jsonStr=“{IsEmailSubscription=true,Name='Ali K',picture='',Id=2534,姓氏=Murat,Email=Email}”