【问题标题】:JSON has extra quotations and slashesJSON 有额外的引号和斜杠
【发布时间】:2018-05-09 16:54:12
【问题描述】:

编辑:这不是上述问题的重复,因为主要问题不是多余的斜杠 - 它是无法通过单个 replaceAll 删除的多余引号。

我使用以下代码将我的 FCM 响应转换为 JSON 格式:

public void onMessageReceived(RemoteMessage remoteMessage)
{
    try
    {
        Map<String, String> params = remoteMessage.getData();

        if(params != null)
        {
            JSONObject jsonObject = new JSONObject(params);
            Object notificationObject = parseJson(jsonObject.toString());

            if(notificationObject instanceof ClientRequestAcceptedModel)
           {
                Log.d(TAG, ((ClientRequestAcceptedModel) notificationObject).getFeedback());
            }
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

我得到以下信息:

{
    "notification_type": "request_accepted",
    "partner_information": "{\"zip\":\"24000\",\"country\":\"canada\",\"address\":\"any raw address\",\"city\":\"some-city\",\"device_meta\":{\"device_id\":\"av0384yuhyiush23768\",\"device_type\":\"android\"},\"last_name\":\"Ahmed1\",\"created_at\":\"2018-04-04 16:28:59\",\"avatar\":\"some image path\",\"partner\":1,\"password_hash\":\"yasir123\",\"last_modefied\":\"2018-04-04 16:28:59\",\"phone_number\":\"+921234567890\",\"location\":{\"latitude\":\"1234567\",\"longitude\":\"1234567\"},\"id\":2,\"first_name\":\"Yasir1\",\"email\":\"yasirahmed15@yopmail.com\",\"customer\":1,\"status\":1}",
    "feedback": "request accepted",
    "request_information": "{\"request_type\":\"custom\",\"request_quotation\":true,\"created_at\":\"2018-05-07 15:57:13\",\"media\":[{\"body\":\"base64string\",\"type\":\"image\"},{\"body\":\"base64string\",\"type\":\"video\"},{\"body\":\"base64string\",\"type\":\"audio\"}],\"schedule_date\":\"0000-00-00\",\"client_id\":2,\"pStatus\":0,\"partner_id\":2,\"schedule_time_from\":\"00:00:00\",\"updated_at\":\"0000-00-00 00:00:00\",\"schedule_time_to\":\"00:00:00\",\"skill\":{\"name\":\"Pipe Fitting\",\"id\":\"1\"},\"extra_notes\":\"some extra notes\",\"request_location\":{\"address\":\"Some raw address of the client if any\",\"latitude\":\"1234567\",\"longitude\":\"1234567\"},\"id\":23,\"status\":0}"
}

如您所见,有大量额外的 \(斜杠) 和一些额外的 "(引号)。我必须使用以下内容将其转换为有效的 JSON:

JSONObject jsonObject = new JSONObject(params);
String modifier = jsonObject.toString().replaceAll("\\\\", "");
String modifier2 = modifier.replace("\"{\"", "{\"");
String modifier3 = modifier2.replace("}\"", "}");

有什么方法可以正确地做到这一点吗?我不能查看所有 JSON 并寻找要替换/修复的东西。

编辑:这里是对象

public class ClientRequestAcceptedModel
{
    @Json(name = "feedback") private String feedback;
    @Json(name = "partner_information") private UserModel partnerInformation;
    @Json(name = "request_information") private RequestInformationModel requestInformation;
}

public class RequestInformationModel
{
    @Json(name = "id") private String id;
    @Json(name = "client_id") private String clientId;
    @Json(name = "partner_id") private String partnerId;
    @Json(name = "skill_id") private String skillId;
    @Json(name = "latitude") private String latitude;
    @Json(name = "longitude") private String longitude;
    @Json(name = "address") private String address;
    @Json(name = "request_type") private String requestType;
    @Json(name = "request_quotation") private Boolean requestQuotation;
    @Json(name = "extra_notes") private String extraNotes;
    @Json(name = "status") private String status;
    @Json(name = "created_at") private String createdAt;
    @Json(name = "updated_at") private String updatedAt;
    @Json(name = "pStatus") private String pStatus;
}

编辑:在下面添加用户请求的模型

    public class RequestInformationModelAdapter extends JsonAdapter<RequestInformationModel>
{
    @Override
    public RequestInformationModel fromJson(JsonReader reader) throws IOException
    {
        Moshi moshi = new Moshi.Builder().build();
        JsonAdapter<RequestInformationModel> jsonAdapter = moshi.adapter(RequestInformationModel.class);

        return jsonAdapter.fromJson(reader.nextString());
    }

    @Override
    public void toJson(JsonWriter writer, RequestInformationModel value) throws IOException
    {
        Moshi moshi = new Moshi.Builder().build();
        JsonAdapter<RequestInformationModel> jsonAdapter = moshi.adapter(RequestInformationModel.class);

        writer.value(jsonAdapter.toJson(value));
    }
}

【问题讨论】:

  • 您是否尝试在日志中打印jsonObject
  • 不,我通过调试器得到了它的值。
  • @NileshRathod 这不是重复的。删除斜线不是主要问题,它是引号。
  • 无论你的数据类是什么,都是不正确的。或者后端正在为 partner_information 和 request_information 发送转义的 json 值。看起来你甚至没有使用 Moshi。此外,您不应该使用这样的 Object 类,instanceof 是一种代码味道。
  • @AfzalivE 添加了这些类。 UserModel 类很好(它已经在其他地方使用并且可以使用)。

标签: android json firebase firebase-cloud-messaging


【解决方案1】:

jsonAdapter.fromJson(jsonString)被调用时,它会自动转换所有匹配的类型,而对于不自动匹配的类型(比如String而不是嵌套的JsonObject),它会抛出异常。因此,您需要告诉它如何使用自定义适配器从该字符串转换为自定义类型。

现在你应该可以自己做另一件事了。

    Moshi moshi = new Moshi.Builder().add(RequestInformationModel.class, new RequestInformationModelAdapter()).build();
    JsonAdapter<ClientRequestAcceptedModel> jsonAdapter = moshi.adapter(ClientRequestAcceptedModel.class);

    ClientRequestAcceptedModel clientRequestAccepted;
    try {
        clientRequestAccepted = jsonAdapter.fromJson(json);
        System.out.println(clientRequestAccepted);

    } catch (IOException e) {
        e.printStackTrace();
    }

下面这个类负责将嵌套的json转换为RequestInformationModel。您必须再次告诉 moshi 将此字符串转换为哪个类。

    public class RequestInformationModelAdapter extends JsonAdapter<RequestInformationModel> {

        @Override
        public RequestInformationModel fromJson(JsonReader reader) throws IOException {
            Moshi moshi = new Moshi.Builder().build();
            JsonAdapter<RequestInformationModel> jsonAdapter = moshi.adapter(RequestInformationModel.class);

            return jsonAdapter.fromJson(reader.nextString());
        }

        @Override
        public void toJson(JsonWriter writer, RequestInformationModel value) throws IOException {
            Moshi moshi = new Moshi.Builder().build();
            JsonAdapter<RequestInformationModel> jsonAdapter = moshi.adapter(RequestInformationModel.class);

            writer.value(jsonAdapter.toJson(value));
        }
    }

您真的应该先尝试使用 Moshi。您在问题中的示例甚至没有使用它。

【讨论】:

  • 我试过你提供的代码。不工作。我得到了相同的“预期 BEGIN_OBJECT,但在路径 $.partner_information 上是 STRING”
  • 问题出现在使用 Moshi 之前,这就是我没有添加该代码的原因。我从 jsonObject.toString() 得到的“字符串”有额外的引号和斜杠。它们是问题所在,而不是后续的解析。
  • 那是因为您必须为合作伙伴信息做同样的事情(使用自定义适配器)。我已经说过了,你有一个格式错误的 json,它没有正确嵌套。在后端修复 json 或使用答案中提供的解决方案之一。错误说明很清楚,它需要一个用于合作伙伴信息的 json 对象,而 json 只有一个字符串。
  • 非常感谢您的帮助。为另一个模型写了一个类似的适配器并且它工作。标记你的答案正确。
  • @chitgoks 当然,添加到问题中。
【解决方案2】:

我从未使用过 Moshi,但据我所见,它将 partner_informationrequest_information 序列化为 String 而不是 JSONbject。检查您的父模型配置以查看注释是否正确。

【讨论】:

  • 它们已正确注释。
  • 您能分享您尝试序列化的实际父模型吗?
  • 添加了对象。
猜你喜欢
  • 1970-01-01
  • 2016-12-02
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 2022-01-10
  • 2015-02-27
  • 1970-01-01
  • 2017-10-01
相关资源
最近更新 更多