我正在为Android构建一个RESTful客户端,我对Jackson有疑问.
我得到以下JSON响应:
{
    "cars": [
        {
            "active": "true",
            "carName": "××× ×'פ ס××××§×",
            "categoryId": {
                "licenseType": "××××××",
                "licenseTypeId": "1"
            },
            "id": "1401268",
            "insuranceDate": "2011-07-05T00:00:00+03:00",
            "lessonLength": "45",
            "licenseDate": "2011-07-05T00:00:00+03:00",
            "price": "100",
            "productionYear": "2009-07-05T00:00:00+03:00"
        },
        {
            "active": "true",
            "carName": "××©× ×××",
            "categoryId": {
                "licenseType": "×ש××ת",
                "licenseTypeId": "4"
            },
            "id": "1589151",
            "insuranceDate": "2011-04-13T00:00:00+03:00",
            "lessonLength": "30",
            "licenseDate": "2011-04-13T00:00:00+03:00",
            "price": "120",
            "productionYear": "2004-04-12T00:00:00+03:00"
        },............. etc
Run Code Online (Sandbox Code Playgroud)
每个都是一个类似汽车的汽车:
public class Cars implements Serializable {
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String carName;
    private …Run Code Online (Sandbox Code Playgroud) 在我的应用程序中 - 我使用JSON进行序列化,到目前为止 - 我使用的是GSON.好吧,它有点慢,尤其是我加载对象的初始登录.
我探索了选择并找到了杰克逊.我通过循环和反序列化1000个样本对象进行了快速测试.杰克逊的速度提高了3倍-5倍.
现在,我构建了包装器,我可以在库之间切换,并开始测试,同时并排查看我从每个库得到的内容.这是我的代码:
public static <T> T fromJson(String json, Class<T> classOfT) throws Exception
    {
        T returnObject;
        Long milliseconds = (new Date()).getTime();
        returnObject = MyGsonWrapper.getMyGson().fromJson(json, classOfT);
        Long gsonTime = (new Date()).getTime() - milliseconds;
        milliseconds = (new Date()).getTime();
        returnObject = MyJacksonWrapper.getMyJson().readValue(json, classOfT);
        Long jacksonTime = (new Date()).getTime() - milliseconds;
if (gsonTime < jacksonTime)
        {
            Log.d(LOG_TAG, "------------- GSON Wins by " + Long.toString(jacksonTime - gsonTime) + " object: " + classOfT.getName());
        }
        else
        {
            Log.d(LOG_TAG, "------------- Jackson Wins by …Run Code Online (Sandbox Code Playgroud) 我正在创建一个Android应用程序,它应该将Json从文件或url解析为jsonarray和jsonobjects.问题是我的json是3.3 MB,当我使用一个简单的代码时,就像这样:(现在无法访问我的真实代码,因为我在工作中,从教程中复制了一些代码;因此可能会有一些错误)
(假设我已经拥有输入流内容)
InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
String twitterfeed = builder.toString();
}
JSONArray jsonArray = new JSONArray(twittefeed);
            Log.i(ParseJSON.class.getName(),
                    "Number of entries " + jsonArray.length());
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Log.i(ParseJSON.class.getName(), jsonObject.getString("text"));
Run Code Online (Sandbox Code Playgroud)
当我在我的Android设备上运行此代码时,我将字符串解析为jsonArray时出现OutOfMemory错误.我记录了一些东西,我发现我的总字符串是17 MB(一个3.3 MB的json文件?!)当我使用一个小的json文件,如twitterfeed左右,代码工作正常.当我在我的内存中得到这个17 MB的字符串时,我无法解析json,因为那时我的内存耗尽了.
经过大量的研究,我发现杰克逊可能是我的解决方案,因为我知道可以解析输入流.这应该有帮助,因为我不需要记忆中的17 mb字符串; 这不是我认为最有效的方式......但是我无法明白这一点真的会起作用,并且没有让它自己运行.有谁知道这真的会起作用,我在哪里可以找到一个教程?
我找到了"createJsonParser - public JsonParser createJsonParser(InputStream in)"并认为这是我的方式......但我不知道如何在我的代码中实现这一点,并且找不到示例.有谁知道这是如何工作的?
我正在尝试使用org.codehaus.jackson.map.deser.std.StdDeserializer自定义反序列化.
我的主要目标是能够连接到Jetty的JSON处理结构并使用Jackson而不是默认的JettyJSON.
所以现在,我正在测试是否有效.
我有一个测试,试图读取一个简单的JSON字符串并将其转换为Presence对象.
public void testBasicJson() throws JsonParseException,
        JsonMappingException,
        IOException {
    ObjectMapper mapper = new ObjectMapper();
    JsonObjectDeserializer jod = new JsonObjectDeserializer();
    SimpleModule module = new SimpleModule("JsonObjectDeserializer",
        new Version(1, 0, 0, null));
    module.addDeserializer(JsonObject.class, jod);
    mapper.registerModule(module);
    //formatted for easy reading
    String jsonSimple = "{
        \"userEmail\":\"user1@lab.com\",
        \"type\":\"presence\",
        \"domain\":\"lab.com\"
    }";
    JsonObject pres = mapper.readValue(jsonSimple, JsonObject.class);
    System.out.println(pres.toString());
}
Run Code Online (Sandbox Code Playgroud)
Presence类是:
public class Presence extends JsonObject {
    private static final long serialVersionUID    = 1L;
    protected String userEmail;
    protected String domain;
    protected String type;
    public …Run Code Online (Sandbox Code Playgroud) 我正在研究使用 Retrofit2 和 RxJava 的 Java 8 REST 客户端设置。使用时GsonConverterFactory一切都会按预期进行。当切换到 a 时JacksonConverterFactory,我根本看不到任何结果(但也不例外)。根据日志,REST 调用本身是正常的。
GitHub上的完整示例。
我使用 lib jackson-module-kotlin 将 json 字符串解析为对象。
我的问题是,当我将字符串解析为 enum 时,当我使用 intellij 启动时,我有以下堆栈跟踪:
引起原因:kotlin.reflect.jvm.internal.KotlinReflectionInternalError:尚未完全支持内置 Kotlin 类型的反射。未找到公共最终 val 名称的元数据:kotlin.Enum[DeserializedPropertyDescriptor@212b316a] 中定义的 kotlin.String
我用maven启动的时候没有这个问题。
我使用 kotlin 1.1.51,使用 intellij kotlin 插件 1.2.0-release-IJ2017.3-1,我的目标是 JVM 1.8,我使用 jackson-module-kotlin 版本 2.8.7
我应该怎么办?
 enum class CType { DEAL, FILE }
 data class Code(val code: String, val type: CType)
 fun testDeserialization() {
    val mapper = jacksonObjectMapper()
    // following line throws an exception:
    mapper.readValue("""{"code":"A","type":"DEAL"}""", Code::class.java)
 }
Run Code Online (Sandbox Code Playgroud) 当我使用 Include.NON_NULL 时,错误响应是错误的,如果我使用 Include.NON_DEFAULT 时,状态 200 的响应是错误的
这就是我正在寻找的:
状态:200 正常
{
        "adultMovie": false,
        "backdropPathMovie": "/2U3hyiVzzhYzS6j9fcdVW4mO4Uk.jpg",
        "originalLanguageMovie": "en",
        "originalTitleMovie": "Fire"
} 
Run Code Online (Sandbox Code Playgroud)
状态:400
{
    "errors": [
        {
            "typeId": "FIELD_VALIDATION_ERRORS",
            "field": "idMovie",
            "message": "Invalid value of `fff` provided"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止尝试过的:我的模型:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Movie implements Serializable {
    private static final long serialVersionUID = -3515253168981789136L;
    private boolean adultMovie;
    private String backdropPathMovie;
    private String originalLanguageMovie;
    private String originalTitleMovie;
    private Set<Error> errors;
}
Run Code Online (Sandbox Code Playgroud)
状态:200 正常
{
    "adultMovie": false,
    "backdropPathMovie": "/2U3hyiVzzhYzS6j9fcdVW4mO4Uk.jpg",
    "originalLanguageMovie": "en",
    "originalTitleMovie": "Fire" …Run Code Online (Sandbox Code Playgroud) 我有带有继承的 kotlin 类:
abstract class Classification(
        val accuracy: Double
)
Run Code Online (Sandbox Code Playgroud)
@Document
class OrderForm(
        @Id
        val id: String,
        accuracy: Double,
        val customerNumber: String,
        val orders: List<Order>
) : Classification(accuracy)
Run Code Online (Sandbox Code Playgroud)
我实现了序列化测试:
internal class OrderFormTest : Logging {
    private val objectMapper = ObjectMapper().registerKotlinModule()
    @Test
    fun canBeSerialisedToJsonAndBack() {
        val expected = OrderForm(
                "123_ID",
                94.77,
                "123_CUSTOMER",
                listOf(
                        Order(
                                0.0,
                                OrderNumber(
                                        10.0,
                                        123456789L),
                                OrderSize(
                                        99.99,
                                        "38/40"),
                                OrderAmount(
                                        100.0,
                                        7),
                                OrderPrice(
                                        50.0,
                                        999.99),
                                OrderPage(
                                        23.29343,
                                        100)
                        ),
                        Order(
                                0.0,
                                OrderNumber(
                                        10.0,
                                        123456789L),
                                OrderSize(
                                        99.99,
                                        "38/40"),
                                OrderAmount(
                                        100.0, …Run Code Online (Sandbox Code Playgroud) 我正在尝试实现一个非常基本的 Spring Boot Web 应用程序。我在@RequestBody.
在addCustomer方法中,我只想绑定/映射firstName和lastName字段并忽略Id字段,即使客户端响应JSON 具有该字段也是如此。
在updateCustomer方法中,我需要映射包括Id在内的所有字段,因为我需要Id字段来更新实体。
我怎样才能忽略@RequestBody.
@RestController
@RequestMapping("/customer-service")
public class CustomerController {
    @Autowired
    CustomerServiceImpl customerService; 
    //This method has to ignore "id" field in mapping to newCustomer
    @PostMapping(path = "/addCustomer")
    public void addCustomer(@RequestBody Customer newCustomer) {
        customerService.saveCustomer(newCustomer);
    }
    //This method has to include "id" field as well to updatedCustomer
    @PostMapping(path = "/updateCustomer")
    public void updateCustomer(@RequestBody Customer updatedCustomer) {
        customerService.updateCustomer(updatedCustomer);
    }
} …Run Code Online (Sandbox Code Playgroud) 我有以下 api
  @GetMapping(value = "/employees")
    public List<Employee> getEmployees(
        @RequestParam(value = "mode", required = false) final EmployeeMode mode) {
        //calling service from here
    }
Run Code Online (Sandbox Code Playgroud)
我将 EmployeeMode 枚举作为 requestParam。
public enum EmployeeMode {
    REGULAR,
    ALL,
    TEMPROARY
}
Run Code Online (Sandbox Code Playgroud)
我想接受不区分大小写的请求。尝试使用@JsonAlias、@JsonCreator和objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true);。spring.jackson.mapper.accept-case-insensitive-enums: true对我来说没有任何作用。
我正在使用 Spring Boot 2.5.5。
如何使用 requestParam 接受不区分大小写的请求?如果 requestParam 为空/null,则需要将默认枚举设置为 ALL。