标签: objectmapper

通过 ObjectMapper 映射 Alamofire responseJSON

注意:我需要使用 ObjectMapper,而不是 AlamoFireObjectMapper。

如何在不使用 JSON 的情况下从responseJSON 数据映射到用户?以下尝试从responseJSON 到jsonn,然后再次返回到data(作为用户)。我想一定有办法吧?

或者我应该使用 AlamoFire 的responseData?

public class User: Mappable {
    var username: String?

    required public init?(map: Map) {

    }

    // Mappable
    public func mapping(map: Map) {
        username    <- map["username"]
    }
}


    Alamofire.request(
        url,
        method: .get,
        headers: headers_employees).responseJSON {
            response in
        // Map via ObjectMapper
        let [User] = Mapper<User>().map(JSONString: JSONString)

   }
Run Code Online (Sandbox Code Playgroud)

ios alamofire objectmapper

5
推荐指数
1
解决办法
4594
查看次数

Jackson ObjectMapper 设置 JsonFormat.Shape.ARRAY 不带注释

我需要使用两个 jackson 2 对象映射器。两个映射器都使用同一组类。首先,我需要使用标准序列化。在第二个中,我想对所有类使用 ARRAY 形状类型(请参阅https://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonFormat.Shape.html#ARRAY)。

但我想为我的第二个 ObjectMapper 全局设置此功能。类似mapper.setShape(...)

怎么做?

更新:

我找到了一种覆盖该类配置的方法:

mapper.configOverride(MyClass.class)
   .setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.ARRAY));
Run Code Online (Sandbox Code Playgroud)

所以我可以使用 Reflection API 更改我的所有类。

尴尬的是我覆盖了全局设置,但又不能直接设置。

java spring json jackson objectmapper

5
推荐指数
1
解决办法
3467
查看次数

性能差异 - Jackson ObjctMapper.writeValue(writer, val) 与 ObjectMapper.writeValueAsString(val)

以下两者之间有显着的性能差异吗?

String json = mapper.writeValueAsString(searchResult);
response.getWriter().write(json);
Run Code Online (Sandbox Code Playgroud)

mapper.writeValue(response.getWriter(), searchResult);
Run Code Online (Sandbox Code Playgroud)

jackson fasterxml objectmapper jackson2 jackson-databind

5
推荐指数
1
解决办法
4061
查看次数

使用 Jackson API 将 JSON 记录转换为 LinkedHashMap&lt;String,String&gt;

我有一个 JSON 文件(它包含一个 JSON 对象数组。)我试图逐个对象地读取它。我需要将每个对象转换为LinkedHashMap<String,String>键和值都是字符串的对象。请注意,即使 JSON 对象包含非字符串值 ( Integer/Boolean),我也希望 myLinkedHashMap包含字符串。

这是我的 JSON 文件 ( films.json):

[
  {
    "name": "Fight Club",
    "year": 1999,
  }
]
Run Code Online (Sandbox Code Playgroud)

现在,它有 1 个对象。我想将其转换为LinkedHashMap<String,String>.

因此,对于上面的示例,我LinkedHashMap应该包含(对于第一个 JSON 对象):

“名称”:“搏击俱乐部”

“年份”:“1999”

注意年份是String在 中LinkedHashMap而不是 中Integer

这就是我尝试过的。

Map<String, Object> myLinkedHashMap;

JsonParser jsonParser = new JsonFactory().createParser(new File("films.json"));
jsonParser = new JsonFactory().createParser(new File(filePath));
jsonParser.nextToken();

ObjectMapper  mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

while(jsonParser.nextToken() != JsonToken.END_ARRAY){
    myLinkedHashMap  = …
Run Code Online (Sandbox Code Playgroud)

java json jackson objectmapper

5
推荐指数
1
解决办法
7720
查看次数

RestAssured 不尊重 Quarkus 中的 ObjectMapper 配置

我对 Quarkus 应用程序中的配置进行了非常简单的调整ObjectMapper,如 Quarkus 指南所述:

@Singleton
public class ObjectMapperConfig implements ObjectMapperCustomizer {

    @Override
    public void customize(ObjectMapper objectMapper) {
        objectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
        objectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
        objectMapper.registerModule(new JavaTimeModule());
    }

}
Run Code Online (Sandbox Code Playgroud)

我这样做是为了用@JsonRootName注释包装/解开我的对象:

@RegisterForReflection
@JsonRootName("article")
public class CreateArticleRequest {

    private CreateArticleRequest(String title, String description, String body, List<String> tagList) {
        this.title = title;
        this.description = description;
        this.body = body;
        this.tagList = tagList;
    }

    private String title;
    private String description;
    private String body;
    private List<String> tagList;

    ... 

}
Run Code Online (Sandbox Code Playgroud)

当针对我的实际 API 时,这工作得很好curl,但是每当我在其中一个测试中使用 RestAssured 时,RestAssured 似乎不尊重我的 …

java rest-assured objectmapper quarkus

5
推荐指数
1
解决办法
1942
查看次数

io.mockk.MockKException:使用mockk通过ObjectMapper.readValue()模拟对象列表时没有找到答案?

有类似的问题,但没有专门涉及 kotlin、mockk 和使用 objectMapper.readValue 读取对象列表。

给定一个方法:

fun someMethod(message: Message): List<Animal> = objectMapper.readValue(
        String(message.body),
        object : TypeReference<List<Animal>>() {}
)
Run Code Online (Sandbox Code Playgroud)

我试图在这里嘲笑它:

@Test
fun `test you filthy animals`() {
    ...
    val animals: List<Animal> = emptyList()
    every { objectMapper.readValue<List<Animal>>(
       any<String>(), 
       any<Class<List<Animal>>>()
    ) } returns animals
    ...
}
Run Code Online (Sandbox Code Playgroud)

但这没有用。我收到以下错误:

io.mockk.MockKException: no answer found for: ObjectMapper(#72).readValue(
     somebody,  
     be.kind.to.Nature$someMethod$animals$1@46b2a11a
)
Run Code Online (Sandbox Code Playgroud)

半停。

mocking kotlin objectmapper mockk

5
推荐指数
1
解决办法
2038
查看次数

映射到使用Alamofire ObjectMapper显示nil的Swift对象问题

我是iOS和Swift开发环境的新手.我试图使用Alamofire来提取JSON和AlamofireObjectMapper,以便将检索到的JSON集合映射回我的Swift对象.

问题是我能够通过Alamofire请求获取JSON并显示计数,但映射部分似乎显示为零.是我错过了什么.感谢帮助.

模型类

import UIKit
import CoreLocation
import ObjectMapper

class BranchObjectMapper : Mappable {
    // MARK: Properties
    var id: Int?
    var cityId: Int?
    var areaId: Int?
    var name: String?
    var nameAr: String?
    var branchAddr: String?
    var branchAddr2: String?
    var location: CLLocation?

    required init?(_ map: Map) {
        mapping(map)
    }

    func mapping(map: Map) {
        id     <- map["id"]
        cityId    <- map["cityId"]
        areaId  <- map["areaId"]
        name  <- map["name"]
        nameAr  <- map["nameAr"]
        branchAddr  <- map["branchAddr"]
        branchAddr2  <- map["branchAddr2"]
        location  <- map["location"]
    }

}
Run Code Online (Sandbox Code Playgroud)

请求参加 viewDidLoad() …

json ios alamofire swift2 objectmapper

4
推荐指数
1
解决办法
6801
查看次数

如何在序列化期间排除ObjectMapper中的字段?

所以我有一个简单的类,如下所示:

class User: NSObject {

  var name = ""
  var phoneNumber = ""

  override func mapping(map: Map) {
    super.mapping(map)
    name          <- map["name"]
    phoneNumber   <- map["phoneNumber"]
  }

}
Run Code Online (Sandbox Code Playgroud)

JSON包含这些字段的响应转换为对象时,这非常有用。但是我想在序列化回时排除一个字段JSON。我怎样才能做到这一点?假设我只想发送name和忽略phoneNumber。这可能吗?似乎是一个非常合理的用例,但是我还没有找到解决方案。

json http ios swift objectmapper

4
推荐指数
1
解决办法
1046
查看次数

AWS DynamoDB:无法取消转换属性错误

我有一个问题,无法解决。我已经在KitchenService中创建了CRUD方法。我有addProduct等方法,这些方法都可以正常工作。.但是我在使用Product类字段的地方有Recipe类。

我的addRecipe方法:

public Recipe addRecipe (Recipe recipe){

    List<RecipeElement> recipeElements = recipe.getRecipeElements();
    for (RecipeElement recipeElement : recipeElements) {
        String id = recipeElement.getProduct().getId();
        Product product = databaseController.get(Product.class, id);
        recipeElement.setProduct(product);
    }

    databaseController.saveRecipe(recipe);
    logger.log("Recipe created");

    return recipe;
Run Code Online (Sandbox Code Playgroud)

构建成功,所以我想在POSTMAN中对其进行测试,这就是我发送的JSON Witch的外观:

{"id":null,"name":"test3","labels":["GLUTEN_FREE"],"author":{"name":"Plejer Anno?n","id":"testID2"},"media":{"name":"heheszki","url":"http://blabla.pl","mediaType":"IMAGE"},"recipeElements":[{"product":{"id":"ecacaf36-29a2-41c6-942e-be5a715ed094"},"weight":"100"}],"approved":false}
Run Code Online (Sandbox Code Playgroud)

然后我得到“消息”:“内部服务器错误”,所以我正在检查日志,这就是我在这里发现的内容:

Product[Media]; could not unconvert attribute: com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException

Caused by: com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: could not invoke public void pl.javamill.model.kitchen.Product.setMedia(pl.javamill.model.common.Media) on class pl.kitchen.Product with value {name=heheszki, url=http://blabla.pl, mediaType=IMAGE} of type class java.util.LinkedHashMap
Run Code Online (Sandbox Code Playgroud)

这是食谱类的外观:

@DynamoDBTable(tableName = "recipe")
public class Recipe extends Request {
/**
 * Id of kitchen …
Run Code Online (Sandbox Code Playgroud)

java json amazon-web-services amazon-dynamodb objectmapper

4
推荐指数
1
解决办法
4818
查看次数

从日期格式中排除毫秒(杰克逊+ Java 8日期)

我试图弄清楚为什么杰克逊(2.9.5)格式错误地来自Java 8。

data class Test(
        val zonedDateTim: ZonedDateTime = ZonedDateTime.now(),
        val offsetDateTim: OffsetDateTime = OffsetDateTime.now(),
        val date: Date = Date(),
        val localDateTime: LocalDateTime = LocalDateTime.now()
)

val mapper = ObjectMapper().apply {
    registerModule(KotlinModule())
    registerModule(JavaTimeModule())
    dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
    enable(SerializationFeature.INDENT_OUTPUT)
}

println(mapper.writeValueAsString(Test()))
Run Code Online (Sandbox Code Playgroud)

从我提供的日期格式中,我希望得到的日期格式没有毫秒,但是结果看起来像这样:

{
  "zonedDateTim" : "2018-07-27T13:18:26.452+02:00",
  "offsetDateTim" : "2018-07-27T13:18:26.452+02:00",
  "date" : "2018-07-27T13:18:26",
  "localDateTime" : "2018-07-27T13:18:26.452"
}
Run Code Online (Sandbox Code Playgroud)

非常感谢您的帮助。

最好,丹尼尔

java date jackson kotlin objectmapper

4
推荐指数
1
解决办法
728
查看次数