无法在Java中解析表单数据请求中的类型

问题描述 投票:-1回答:1

虽然从Android设备检索到我的Spring引导控制器的HTTP请求,但在解析表单数据中的Typed对象时遇到了问题。

我需要发送包含两个文件和一些数据的多部分请求,因此我决定为此使用表单数据。

现在与文件一起发送的数据是原始数据,我可以在控制器中对其进行解析,但是如果我尝试发送Type(例如List或仅是Animal.class),则会出现异常,例如:

Mismatched parameters; can't parse to string

是否不可能以表单数据发送复杂对象。我该如何解决以上问题。

java spring-boot multipartform-data form-data
1个回答
0
投票

我知道这不是直接的答案,但这是一个更好的解决方案。您应该将所有数据压缩为具有固定格式的字节数组。序列化需要很长时间,如果您知道要发送的数据,则无需使用这种非特定算法,与自己进行序列化相比,它需要很长时间。我实际上不知道您要在Animal类中发送什么数据,但是可以说您发送的是物种(字符串变量),年龄和代表该动物是否完全生长的布尔值。

class Animal {
    /* Fields and Constructors here */

    public static byte[] toByteArray(Animal a) {
        byte[] arr = new byte[a.name.length() + 4 /*(length of array)*/ + 4 /*(the age)*/ + 1 /*(fully-grown)*/];

        arr[0] = a.name.length() >> 24 & 0xff;
        arr[1] = a.name.length() >> 16 & 0xff;
        arr[2] = a.name.length() >> 8 & 0xff;
        arr[3] = a.name.length() & 0xff;

        for (int i = 0; i < a.name.length(); i++) {
            arr[i + 4] = a.name.charAt(i);
        }

        arr[a.name.length() + 4] = a.age >> 24 & 0xff;
        arr[a.name.length() + 5] = a.age >> 16 & 0xff;
        arr[a.name.length() + 6] = a.age >> 8 & 0xff;
        arr[a.name.length() + 7] = a.age & 0xff;

        arr[a.name.length() + 8] = a.grown? 0x1 : 0x0;
    }
}

反序列化也可以这样做,但是反过来。我不知道我是否忘记了一些演员表,但我敢肯定你能弄清楚:)

© www.soinside.com 2019 - 2024. All rights reserved.