考虑如下 Java 对象:
class User {
  String name;
  int age;
  String locationJson; // this is a json already
  //allArgsConstructor, getters & setters
}
所以当我们这样做时
import com.fasterxml.jackson.databind.ObjectMapper;
....
User user = new User("Max", 13, "{\"latitude\":30.0000,\"longitude\":32.0000}");
new ObjectMapper().writeValueAsString(user)), String.class);
我期待类似的事情:
{
  "name": "Max",
  "age": "13",
  "locationJson": {"latitude":30.0000, "longitude":32.0000}
}
相反,我将它作为一个 json 值包裹在双引号中,并用反斜杠跳过,因为它是双 json 化的- 如果这实际上是一个动词 -
{
  "name": "Max",
  "age": "13",
  "locationJson": "{\"latitude\":30.0000, \"longitude\":32.0000}"
}
在我的视图模型中,我有这个属性和方法:
@Published var cats: [Cat] = [] //this gets populated later
当我更新其中一只猫时:
func updateCatQuantity(_ cat:Cat, qty: Int) {
    if let index = cats(of: cat) {
        cats[index].quantity = qty
    }
}
视图不会刷新。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)
    } …我有一个JSON字符串,称为primarySkillStr:
[
  {
    "id": 3,
    "roleIds": [
      2
    ],
    "rating": 2
  }
]
我尝试将其映射到对象,如下所示:
primarySkillList = mapper.readValue(primarySkillStr, 
    new TypeReference<List<PrimarySkillDTO>>() {});
但是当Iam将其转换为a时List,roleIds列表为null。我是在做错什么,还是有其他办法?
这是我的DTO
public class PrimarySkillDTO {
    private Integer id;
    private Integer rating;
    private List<Integer> roleIds;
    private String name;
}
我在PrimarySkillDTO课堂上有以下注释
@Data
@Builder
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
我正在从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"
}
问题出在“消息”属性,而不是持有对象,而是引用对象的字符串
包含
"Message":"{\"key\":\"value\"}"
代替
"Message":{"key":"value"}"
因此没有映射到Message类
我暂时通过接收到字符串变量来解决此问题,然后将其转换
private String Message;
private Message objMessage;
然后
Notification noti = toObject(jsonString, Notification.class);
Message msg = toObject(noti.getMessage(), Message.class);
noti.setObjMessage(msg);
为了进行转换,我正在使用ObjectMapper.readValue(...)
解决此问题的正确方法是什么?
我正在使用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"]
    }
}
我有这个 JSON 结构:
{
   "name": "first",
   "userId": "1" // here is `String` type.
},
{
   "name": "second",
   "userId": 1 // here is `Int` type.
}
映射JSON后,其中的userId值为null 。Username"first"
我怎样才能映射Int/String到Int?
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"}]
ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        String arrayToJson = objectMapper.writeValueAsString(jsonObjlist);
我得到的输出是
[{"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"}}]
期望的输出是
"[{"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"}]"
我有 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"
      },
如何将简单对象映射或转换为这种类型的数组
我使用对象映射器映射数组
public var ownersPeriodArray: [Model] = []
我在这里使用 ObjectMapper 库将 json 转换为我的模型 let model = Mapper().map(JSON: json)
    @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> …我想在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);
错误:
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'
或者这个:
Error detected in application source code: …我有一个具有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
     }
输入json:
{
    "topic":"x111",
    "imageUrl":"http://x.com/x1/x11/x111",
    "duration":"00:00:05"
}
错误:
Can not construct instance of java.time.LocalTime: no …我正在尝试转换下一个字符串:
"{ \"contacts\": [{\"name\":\"1\",\"phone\":\"+123456\"}]}"
到一些自定义对象:
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;
    }
}
此外,此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 …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
      }
   }
]  
机会:
[  
   {  
      "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"
      }
   }
]
如图所示,初始字段在两个(所有)模型中都很常见 - 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? …我们有一类代理与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 …objectmapper ×13
java ×8
json ×8
swift ×4
jackson ×3
ios ×2
spring ×2
alamofire ×1
amazon-ses ×1
amazon-sns ×1
arrays ×1
dart ×1
fasterxml ×1
flutter ×1
generics ×1
spring-boot ×1
string ×1
swiftui ×1