标签: objectmapper

将 Java 对象转换为包含 json 字符串属性的 json 字符串

考虑如下 Java 对象:

class User {

  String name;

  int age;

  String locationJson; // this is a json already

  //allArgsConstructor, getters & setters
}
Run Code Online (Sandbox Code Playgroud)

所以当我们这样做时

import com.fasterxml.jackson.databind.ObjectMapper;
....

User user = new User("Max", 13, "{\"latitude\":30.0000,\"longitude\":32.0000}");

new ObjectMapper().writeValueAsString(user)), String.class);
Run Code Online (Sandbox Code Playgroud)

我期待类似的事情:

{
  "name": "Max",
  "age": "13",
  "locationJson": {"latitude":30.0000, "longitude":32.0000}
}
Run Code Online (Sandbox Code Playgroud)

相反,我将它作为一个 json 值包裹在双引号中,并用反斜杠跳过,因为它是双 json 化的- 如果这实际上是一个动词 -

{
  "name": "Max",
  "age": "13",
  "locationJson": "{\"latitude\":30.0000, \"longitude\":32.0000}"
}
Run Code Online (Sandbox Code Playgroud)

java spring json jackson objectmapper

2
推荐指数
1
解决办法
1806
查看次数

当已发布对象更改时,SwiftUI 视图不会刷新

在我的视图模型中,我有这个属性和方法:

@Published var cats: [Cat] = [] //this gets populated later
Run Code Online (Sandbox Code Playgroud)

当我更新其中一只猫时:

func updateCatQuantity(_ cat:Cat, qty: Int) {
    if let index = cats(of: cat) {
        cats[index].quantity = qty
    }
}
Run Code Online (Sandbox Code Playgroud)

视图不会刷新。didSetoncats不会被调用。Cat我认为这与类而不是结构这一事实有关。它的定义如下:

class Cat: BaseMapperModel, Identifiable, Hashable {
    static func == (lhs: Cat, rhs: Cat) -> Bool {
       return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
    }

    var id = UUID()

    var title: String = ""
    var quantity: Int = 0

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    } …
Run Code Online (Sandbox Code Playgroud)

swift objectmapper swiftui property-wrapper-published

2
推荐指数
1
解决办法
577
查看次数

如何使用ObjectMapper将String转换为java8中的列表?

我有一个JSON字符串,称为primarySkillStr

[
  {
    "id": 3,
    "roleIds": [
      2
    ],
    "rating": 2
  }

]
Run Code Online (Sandbox Code Playgroud)

我尝试将其映射到对象,如下所示:

primarySkillList = mapper.readValue(primarySkillStr, 
    new TypeReference<List<PrimarySkillDTO>>() {});
Run Code Online (Sandbox Code Playgroud)

但是当Iam将其转换为a时ListroleIds列表为null。我是在做错什么,还是有其他办法?

这是我的DTO

public class PrimarySkillDTO {
    private Integer id;
    private Integer rating;
    private List<Integer> roleIds;
    private String name;
}
Run Code Online (Sandbox Code Playgroud)

我在PrimarySkillDTO课堂上有以下注释

@Data
@Builder
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
Run Code Online (Sandbox Code Playgroud)

java jackson objectmapper

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

如何在Java中正确解析SES退回JSON SNS通知

我正在从SNS主题接收JSON,我认为这是不正确的

{
   "Type":"Notification",
   "MessageId":"message-id-is-this",
   "TopicArn":"bouncer.topic.name.here",
   "Message":"{\"notificationType\":\"Bounce\",\"bounce\":{\"bounceType\":\"Permanent\",\"bounceSubType\":\"General\",\"bouncedRecipients\":[{\"emailAddress\":\"bounce@simulator.amazonses.com\",\"action\":\"failed\",\"status\":\"5.1.1\",\"diagnosticCode\":\"smtp; 550 5.1.1 user unknown\"}],\"timestamp\":\"2017-04-24T12:58:05.716Z\",\"feedbackId\":\"feedback.id.is.here\",\"remoteMtaIp\":\"192.168.10.1\",\"reportingMTA\":\"dsn; smtp.link.here\"},\"mail\":{\"timestamp\":\"2017-04-24T12:58:05.000Z\",\"source\":\"senderEmail@domainname.com\",\"sourceArn\":\"arn:aws:ses:us-east-1:someid:identity/some@domain.org\",\"sourceIp\":\"127.0.0.1\",\"sendingAccountId\":\"sending.account.id.is.this\",\"messageId\":\"message-id-is-this\",\"destination\":[\"bounce@simulator.amazonses.com\"]}}",
   "Timestamp":"2017-04-24T12:58:05.757Z",
   "SignatureVersion":"1",
   "Signature":"signature.link",
   "SigningCertURL":"certificate.link.here",
   "UnsubscribeURL":"un.subscribe.link"
}
Run Code Online (Sandbox Code Playgroud)

问题出在“消息”属性,而不是持有对象,而是引用对象的字符串

包含

"Message":"{\"key\":\"value\"}"
Run Code Online (Sandbox Code Playgroud)

代替

"Message":{"key":"value"}"
Run Code Online (Sandbox Code Playgroud)

因此没有映射到Message类

我暂时通过接收到字符串变量来解决此问题,然后将其转换

private String Message;
private Message objMessage;
Run Code Online (Sandbox Code Playgroud)

然后

Notification noti = toObject(jsonString, Notification.class);
Message msg = toObject(noti.getMessage(), Message.class);
noti.setObjMessage(msg);
Run Code Online (Sandbox Code Playgroud)

为了进行转换,我正在使用ObjectMapper.readValue(...)

解决此问题的正确方法是什么?

java json amazon-sns amazon-ses objectmapper

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

如何使用ObjectMapper映射不同类型?

我正在使用ObjectMapper将 JSON 映射到 Swift 对象。

我有以下 Swift 对象:

class User: Mappable {

    var name: String?
    var val: Int?

    required init?(map: Map) { }

    func mapping(map: Map) {
        name <- map["name"]
        val  <- map["userId"]
    }
}
Run Code Online (Sandbox Code Playgroud)

我有这个 JSON 结构:

{
   "name": "first",
   "userId": "1" // here is `String` type.
},
{
   "name": "second",
   "userId": 1 // here is `Int` type.
}
Run Code Online (Sandbox Code Playgroud)

映射JSON后,其中的userId值为null 。Username"first"

我怎样才能映射Int/StringInt

json swift objectmapper

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

如何在 java 中将列表 &lt;JSONObject&gt; 转换为 Json 字符串 (com.amazonaws.util.json.JSONObject)

com.amazonaws.util.json.JSONObject 下面是列表,我想将其转换为 json 字符串。

List<JSONObject> jsonObjlist

[{"Attribute":"EmailAddress","Value":"abc@yahoo.com"}, {"Attribute":"Source","Value":"Missing_Fixed"}, {"Attribute":"mx_Lead_Status","Value":"Registered User"}, {"Attribute":"mx_Age","Value":""}, {"Attribute":"mx_LoginID","Value":"abc@yahoo.com"}, {"Attribute":"mx_Registration_Source","Value":"EMAIL"}]
Run Code Online (Sandbox Code Playgroud)
ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        String arrayToJson = objectMapper.writeValueAsString(jsonObjlist);
Run Code Online (Sandbox Code Playgroud)

我得到的输出是

[{"map":{"Attribute":"EmailAddress","Value":"abc@yahoo.com"}},{"map":{"Attribute":"Source","Value":"Missing_Fixed"}},{"map":{"Attribute":"mx_Lead_Status","Value":"Registered User"}},{"map":{"Attribute":"mx_Age","Value":""}},{"map":{"Attribute":"mx_LoginID","Value":"abc@yahoo.com"}},{"map":{"Attribute":"mx_Registration_Source","Value":"EMAIL"}}]
Run Code Online (Sandbox Code Playgroud)

期望的输出是

"[{"Attribute":"EmailAddress","Value":"abc@yahoo.com"}, {"Attribute":"Source","Value":"Missing_Fixed"}, {"Attribute":"mx_Lead_Status","Value":"Registered User"}, {"Attribute":"mx_Age","Value":""}, {"Attribute":"mx_LoginID","Value":"abc@yahoo.com"}, {"Attribute":"mx_Registration_Source","Value":"EMAIL"}]"
Run Code Online (Sandbox Code Playgroud)

java json objectmapper

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

将 JSON 映射为数组或对象

我有 json 有时会显示数组有时是简单的对象

"ownersPeriod" : [
        {
          "dateTo" : "2013-06-17",
          "dateFrom" : "2012-09-15"
        },
        {
          "dateTo" : "2016-06-30",
          "dateFrom" : "2013-06-17"
        },
        {
          "dateTo" : "",
          "dateFrom" : "2016-06-30"
        }
      ],

"ownersPeriod" : {
        "dateTo" : "",
        "dateFrom" : "2008-03-29"
      },

Run Code Online (Sandbox Code Playgroud)

如何将简单对象映射或转换为这种类型的数组

我使用对象映射器映射数组

public var ownersPeriodArray: [Model] = []
Run Code Online (Sandbox Code Playgroud)

我在这里使用 ObjectMapper 库将 json 转换为我的模型 let model = Mapper().map(JSON: json)

arrays json ios swift objectmapper

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

Java ObjectMapper.readValue 将泛型类型转换为 LinkedHashMap

    @Service
public class PokemonManager implements PokemonService {

    private HttpResponse<String> getStringHttpResponseByUrl(final String url) {
        HttpClient httpClient = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .GET().header("accept", "application/json")
                .uri(URI.create(url)).build();
        HttpResponse<String> httpResponse = null;
        try {
            httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return httpResponse;
    }

    private <T> T getObjectResponse(T t, String url) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            t = objectMapper.readValue(getStringHttpResponseByUrl(url).body(), new TypeReference<>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return t;
    }

    private List<Pokemon> …
Run Code Online (Sandbox Code Playgroud)

java generics spring objectmapper

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

Flutter中的JSON ObjectMapper

我想在Flutter中从JSON序列化/反序列化对象.我知道我可以使用来自这给我字符串基于密钥的LinkedHashMap,但我更感兴趣的是ObjectMapper的方法,使我能够得到输入从反序列化反应.JsonDecoderjson.dart

我尝试使用Flutter的redstone mapper(链接)和可导出的库(链接) - 这两个我都无法正确编译.我相信这个问题与Dart的反射库有关.

如何使用Flutter实现工作的Object-Json Mapper?

示例代码:

class A {

  @Field()
  String b;
}

import 'package:redstone_mapper/mapper.dart';
import 'package:redstone_mapper/mapper_factory.dart';

bootstrapMapper();
var desObj = decodeJson(jsonString, A);
Run Code Online (Sandbox Code Playgroud)

错误:

Starting device daemon...
Running lib/main.dart on Nexus 5X...
Dart snapshot generator failed with exit code 254
Errors encountered while loading: 'dart:mirrors': error: line 1 pos 1: unexpected token 'Unhandled'
Run Code Online (Sandbox Code Playgroud)

或者这个:

Error detected in application source code: …
Run Code Online (Sandbox Code Playgroud)

json jsonserializer dart flutter objectmapper

0
推荐指数
1
解决办法
1754
查看次数

在对象映射器中全局注册模块

我有一个具有duration类型数据成员的Topic 类LocalTime

    @Entity
    @Table(name= "topics")
    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
    property  = "id",
    scope     = Long.class)
    @DynamicInsert(true)
    @DynamicUpdate(true)
    public class Topics implements Serializable {

        private static final long serialVersionUID = -1777454701749518940L;

        @Id
        @Column(name= "id")
        private Long id = Long.parseLong(UUID.randomUUID().toString().substring(0, 8), 16);

        @NotEmpty
        @NotNull
        @Column(name= "topic", columnDefinition = "Text", length = 50000)
        private String topic;

        @Convert(converter = LocalTimeConverter.class)
        private LocalTime duration;

        // getters and setters
     }
Run Code Online (Sandbox Code Playgroud)

输入json:

{
    "topic":"x111",
    "imageUrl":"http://x.com/x1/x11/x111",
    "duration":"00:00:05"
}
Run Code Online (Sandbox Code Playgroud)

错误:

Can not construct instance of java.time.LocalTime: no …
Run Code Online (Sandbox Code Playgroud)

java fasterxml spring-boot objectmapper

0
推荐指数
1
解决办法
8599
查看次数

错误com.fasterxml.jackson.databind.exc.MismatchedInputException:由于输入结束而没有要映射的内容

我正在尝试转换下一个字符串:

"{ \"contacts\": [{\"name\":\"1\",\"phone\":\"+123456\"}]}"
Run Code Online (Sandbox Code Playgroud)

到一些自定义对象:

public class CustomObject{

    private List<Contact> contacts;

    public CustomObject(){

    }

    public CustomObject(List<Contact> contacts) {
        this.contacts = contacts;
    }

    public List<Contact> getContactList() {
        return contacts;
    }

    public void setContactList(List<Contact> contacts) {
        this.contacts = contacts;
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,此CustomObject中还有另一个对象:

public class Contact {

    private String name;
    private String phone;

    public Contact() {
    }

    public Contact(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name …
Run Code Online (Sandbox Code Playgroud)

java string json jackson objectmapper

0
推荐指数
1
解决办法
3752
查看次数

Alamofire ObjectMapper - 从所有模型中提取公共字段并映射它们

api返回的所有模型中都很少有字段.但它们并不是一个单独的对象.他们在其他领域.

两个型号的示例:

事件:

[  
   {  
      "event":{  
         "id":3,
         "company_id":18,
         "archived":false,
         "created_by":229,
         "updated_by":229,
         "owner_id":229,
         "subject":"",
         "start_date":null,
         "end_date":null,
         "name":null,
         "name_class_name":"",
         "related_to":null,
         "related_to_class_name":"",
         "status":"",
         "created_at":"2018-05-07T01:59:38.921-04:00",
         "updated_at":"2018-05-07T01:59:38.921-04:00",
         "custom_nf":false
      }
   }
]  
Run Code Online (Sandbox Code Playgroud)

机会:

[  
   {  
      "opportunity":{  
         "id":4,
         "company_id":18,
         "archived":false,
         "created_by":229,
         "updated_by":229,
         "owner_id":229,
         "account_id":null,
         "name":"",
         "lead_source":"",
         "amount":null,
         "close_date":null,
         "probability":null,
         "stage":"",
         "created_at":"2018-05-07T01:49:55.441-04:00",
         "updated_at":"2018-05-07T01:49:55.441-04:00"
      }
   }
]
Run Code Online (Sandbox Code Playgroud)

如图所示,初始字段在两个(所有)模型中都很常见 - id,company_id,archived,created_by等.
我使用过ObjectMapper有很多项目,但之前没有遇到过.我完全了解处理嵌套模型,但这是一个不同的情况.
虽然我可以通过重复所有模型中的所有常见字段来轻松处理此问题.但这听起来不太好.
我正在寻找一种方法,我可以创建一个包含所有常见字段的单独模型类.但问题是- 如何使用ObjectMapper将其映射到api响应?

举个例子,这就是我创建机会模型的方式:

import UIKit
import ObjectMapper

class Opportunity: NSObject, Mappable {

    var id: Int?
    var companyId: Int?
    var archived: Int? …
Run Code Online (Sandbox Code Playgroud)

json ios swift alamofire objectmapper

0
推荐指数
1
解决办法
150
查看次数

List&lt;Long&gt; 在 Java 中未序列化为 String

我们有一类代理assignedUsers作为列表<>

当我们尝试将对象转换为 JSON 文档时,我们使用的是ObjectMapper writeValueAsString方法,该方法不会将 id 序列化为字符串,而是不会在 JSON 字符串中丢失键assignedUsers

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Agent {
private List<Long> assignedUserIds;
        private String name;

        private static final String json = "{\"name\":\"New Agency\", \"assignedUserIds\":[23,24]}";

        public String getName() {
                return name;
        }

        public void setName(final String name) {
                this.name = name;
        }

        public List<Long> gocuetAssignedUserIds() {
        return assignedUserIds;
        }

        public void setAssignedUserIds(final List<Long> assignedUserIds) {
                this.assignedUserIds = assignedUserIds;
        }

        public …
Run Code Online (Sandbox Code Playgroud)

java serialization objectmapper

0
推荐指数
1
解决办法
57
查看次数