我有一个响应模型,如下所示:
class ResponseModel: Mappable {
var data: T?
var code: Int = 0
required init?(map: Map) {}
func mapping(map: Map) {
data <- map["data"]
code <- map["code"]
}
}
Run Code Online (Sandbox Code Playgroud)
如果json-data不是数组,它可以工作:
{"code":0,"data":{"id":"2","name":"XXX"}}
Run Code Online (Sandbox Code Playgroud)
但如果它是一个数组,它不起作用
{"code":0,"data":[{"id":"2","name":"XXX"},{"id":"3","name":"YYY"}]}
Run Code Online (Sandbox Code Playgroud)
我的映射代码;
let apiResponse = Mapper<ResponseModel>().map(JSONObject: response.result.value)
Run Code Online (Sandbox Code Playgroud)
详情; 我使用这篇文章尝试了这段代码:http://oramind.com/rest-client-in-swift-with-promises/
我试图从URL检索JSON数据,但得到以下错误:
Illegal character ((CTRL-CHAR, code 31)):
only regular white space (\r, \n,\t) is allowed between tokens
Run Code Online (Sandbox Code Playgroud)
我的代码:
final URI uri = new URIBuilder(UrlConstants.SEARCH_URL)
.addParameter("keywords", searchTerm)
.addParameter("count", "50")
.build();
node = new ObjectMapper().readTree(new URL(uri.toString())); <<<<< THROWS THE ERROR
Run Code Online (Sandbox Code Playgroud)
构建的网址是https://www.example.org/api/search.json?keywords=iphone&count=50
这里出了什么问题?我怎样才能成功解析这些数据?
进口:
import com.google.appengine.repackaged.org.codehaus.jackson.JsonNode;
import com.google.appengine.repackaged.org.codehaus.jackson.map.ObjectMapper;
import com.google.appengine.repackaged.org.codehaus.jackson.node.ArrayNode;
import org.apache.http.client.utils.URIBuilder;
Run Code Online (Sandbox Code Playgroud)
示例响应
{
meta: {
indexAllowed: false
},
products: {
products: [
{
id: 1,
name: "Apple iPhone 6 16GB 4G LTE GSM Factory Unlocked"
},
{
id: 2,
name: "Apple iPhone …
Run Code Online (Sandbox Code Playgroud) 我有以下java类
public class TabularDescriptor extends ReportDescriptor {
private String generatorClass;
private String targetClass;
private String name;
private String sublabel;
private String reportName;
private List<MappingMetadata> mappings = null;
private List<TabularColumnGroup> columnGroups = null;
private List<TabularStates> states = null;
:
:
and its getters and settere
Run Code Online (Sandbox Code Playgroud)
对于每个列表,我都有实体类,例如 MappingMetadata、TabularColumnGroup、TabularStates。我想获得这个 pojo 类的 json 数据。我能为它做什么。
还有什么用
public JSONObject toJSON() {
JSONObject ret = new JSONObject();
ret.put("generatorClass", this.generatorClass);
ret.put("targetClass", this.targetClass);
ret.put("name", this.name);
:
:
return ret;
}
Run Code Online (Sandbox Code Playgroud)
无论如何我可以在浏览器上显示我的json内容,如果是的话,我该怎么做?谢谢。
我想将json字符串转换为List<Someclass>
使用jackson json库.
public static List<T> toList(String json, Class<T> type, ObjectMapperProperties objectMapperProperties){
ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper(objectMapperProperties);
try {
return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, type));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
所以,如果我通过Attribute.class
的type
,那么它必须返回List<Attribute>
.
但是,这给了我一个编译时错误
T cannot be resolved to a type
Run Code Online (Sandbox Code Playgroud)
我想泛型部分对我来说并不清楚.任何帮助表示赞赏.
在我的Realm对象模型中,我有一个名为"Event"的对象.每个事件都有一个EventLocatons列表.我试图从json映射这些对象,但EventLocations列表始终为空.对象看起来像这样(为简洁起见,简化了):
class Event: Object, Mappable {
override class func primaryKey() -> String? {
return "id"
}
dynamic var id = ""
var eventLocations:List<EventLocation> = List<EventLocation>()
func mapping(map: Map) {
id <- map["id"]
eventLocations <- map["eventLocations"]
}
}
class EventLocation: Object, Mappable {
override class func primaryKey() -> String? {
return "id"
}
dynamic var id: String = ""
dynamic var name: String = ""
required convenience init?(_ map: Map) {
self.init()
}
func mapping(map: Map) {
id <- map["id"]
name …
Run Code Online (Sandbox Code Playgroud) 我正在使用ObjectMapper将json转换为对象.我的问题是没有正确映射NSDate属性.这是json:
{
"Id":4775,
"Cor":{
"Id":2,
"Nome":"Amarelo",
"HTMLCode":"FFFB00"
},
"Data":"2016-07-25T09:35:00",
"Texto":"test test test",
"Kilometro":547.0
}
Run Code Online (Sandbox Code Playgroud)
这是我可以上映的课程
class RoadWarning : Mappable {
var id: Int?
var color: RoadWarningColor?
var date: NSDate?
var text: String?
var kilometer: Float?
required init?(_ map: Map){
}
func mapping(map: Map) {
id <- map["Id"]
color <- map["Cor"]
text <- map["Texto"]
kilometer <- map["Kilometro"]
date <- (map["Data"], DateTransform())
}
}
Run Code Online (Sandbox Code Playgroud)
问题是date属性始终是1970-01-01.我还看不到我所缺少的东西.你能看出这个映射有什么问题吗?
谢谢
我收到响应后试图将json
对象存储到realm
对象.以下是我写的代码:Objectmapper
Alamofire
func getTodayData() {
Alamofire.request("https://myapipoint.json").responseJSON{ (response) in
guard response.result.isSuccess, let value = response.result.value else {
return
}
let json = JSON(value)
guard let realm = try? Realm() else {
return
}
realm.beginWrite()
for (_, value): (String, JSON) in json {
let tpTodayOb = Mapper<TPToday>().map(JSONObject: value.dictionaryObject)
realm.add(tpTodayOb!, update: true)
}
do {
try realm.commitWrite()
}
catch {
print("Error")
}
}
}
Run Code Online (Sandbox Code Playgroud)
我能够json
从我的服务器映射数据.但是,我的复合键存在问题.这三个变量不是唯一的,但它们的组合是唯一的,所以我不得不compoundKey
用作我的主键.我建立primaryKey
从compoundKey
如下:
public dynamic var compoundKey: String …
Run Code Online (Sandbox Code Playgroud) 使用Jackson将Java对象转换为JSON
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
jsonMessage = mapper.writeValueAsString(object);
Run Code Online (Sandbox Code Playgroud)
结果是字段"参与者"(它是对象实例的一部分)
participants Arrays$ArrayList<E>
Run Code Online (Sandbox Code Playgroud)
被重命名为"participantList"
participantsList":[{"userId":"c1f9c"}]
Run Code Online (Sandbox Code Playgroud)
即"列表"附加到字段名称.我浏览了杰克逊的文档,但没有找到防止这种情况发生的方法.这可能吗?在独立项目中测试上述代码不会导致相同的结果(即不进行重命名).为什么杰克逊表现得像这样?不幸的是,对象是第三方,我无法改变它.
使用Jackson版本2.3.3(使用2.9.0验证相同的行为).
在将 Java 对象转换为 JSON 字符串时,我遇到了 JsonMappingException。以下是完整的异常消息。
com.fasterxml.jackson.databind.JsonMappingException: Not an array: {"type":"record","name":"ClearingSystemMemberIdentification2","namespace":"com.sam.eps.paymentdomain.avro.pacs002","doc":"Schema for com.sam.eps.iso.pacs002.ClearingSystemMemberIdentification2","fields":[{"name":"clearing_system_identification","type":["null",{"type":"record","name":"ClearingSystemIdentification2Choice","doc":"Schema for com.sam.eps.iso.pacs002.ClearingSystemIdentification2Choice","fields":[{"name":"code","type":["null",{"type":"string","avro.java.string":"String"}],"default":null},{"name":"proprietary","type":["null",{"type":"string","avro.java.string":"String"}],"default":null}]}],"default":null},{"name":"member_identification","type":["null",{"type":"string","avro.java.string":"String"}],"default":null}]} (through reference chain: com.sam.eps.paymentdomain.avro.pacs002.Document["fi_to_fi_payment_status_report"]->com.sam.eps.paymentdomain.avro.pacs002.FIToFIPaymentStatusReportV10["group_header"]->com.sam.eps.paymentdomain.avro.pacs002.GroupHeader91["instructed_agent"]->com.sam.eps.paymentdomain.avro.pacs002.BranchAndFinancialInstitutionIdentification6["financial_institution_identification"]->com.sam.eps.paymentdomain.avro.pacs002.FinancialInstitutionIdentification18["clearing_system_member_identification"]->com.sam.eps.paymentdomain.avro.pacs002.ClearingSystemMemberIdentification2["schema"]->org.apache.avro.Schema$RecordSchema["elementType"])
Run Code Online (Sandbox Code Playgroud)
下面是我用来将 Java 对象转换为 JSON 字符串的 java 代码。我尝试启用 ACCEPT_SINGLE_VALUE_AS_ARRAY、ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT 但仍然面临问题。不确定导致JsonMappingException 的原因:不是数组问题。
private String convertObjectToJson(Object request) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(OffsetDateTime.class, new JsonSerializer<OffsetDateTime>() {
@Override
public void serialize(OffsetDateTime offsetDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(offsetDateTime));
}
});
simpleModule.addSerializer(LocalDate.class, new JsonSerializer<LocalDate>() {
@Override
public void serialize(LocalDate localDate, JsonGenerator jsonGenerator, …
Run Code Online (Sandbox Code Playgroud) 我正在使用 maven 和 dropwizard,java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/TSFBuilder
当我启动对象映射器时出错。
尝试通过将com.fasterxml.jackson.core
2.10.0 版添加到 POM来覆盖依赖项(也尝试了其他几个版本),但仍然出现相同的错误。
有什么建议吗?
objectmapper ×10
json ×7
java ×5
jackson ×4
swift ×3
realm ×2
dropwizard ×1
generics ×1
ios ×1
swift3 ×1