- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我从这个link获取Json
我正在使用以下两个 pojo 类进行映射。
1)NewsSource.class
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "status", "sources" })
public class NewsSource {
@JsonProperty("status")
private String status;
@JsonProperty("sources")
private List<Source> sources = null;
@JsonProperty("status")
public String getStatus() {
return status;
}
@JsonProperty("status")
public void setStatus(String status) {
this.status = status;
}
@JsonProperty("sources")
public List<Source> getSources() {
return sources;
}
@JsonProperty("sources")
public void setSources(List<Source> sources) {
this.sources = sources;
}
}
2)Source.class
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "id", "name", "description", "url", "category", "language", "country", "sortBysAvailable" })
public class Source {
@JsonProperty("id")
private String id;
@JsonProperty("name")
private String name;
@JsonProperty("description")
private String description;
@JsonProperty("url")
private String url;
@JsonProperty("category")
private String category;
@JsonProperty("language")
private String language;
@JsonProperty("country")
private String country;
@JsonProperty("sortBysAvailable")
private List<String> sortBysAvailable = null;
//getter setters generated with IDE , and annotated with @JsonProperty too
我使用此代码将 json 映射到 pojo 。
public NewsSource getNewsSource() {
String URL = source_url; //above mentioned url to get json
ObjectMapper omapper= new ObjectMapper();
omapper.setVisibilityChecker(omapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
NewsSource newsSource =null;
try {
String result = restTemplate.getForObject(URL, String.class);
//result is returnning data properly
omapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
newsSource = omapper.readValue(result, NewsSource.class);
//newsSource returnning null
}catch (Exception ex){
System.out.println("oooh exception ");
}
我已经尝试了 this 中提到的许多建议技巧。链接,但没有人为我工作:)
注意:我正在为 Jackson 使用以下 Maven 依赖项。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
如有任何建议,我们将不胜感激。提前致谢
更新我使用了以下代码。
private static Object getJsonObject(String str) {
Object obj = null;
try {
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
if (str != null) {
obj = mapper.readValue(str, NewsSource.class);
}
} catch (Exception exc) {
exc.printStackTrace();
}
System.out.println("json obj:===>" + obj);
return obj;
}
public NewsSource getNewsSource() {
String URL = source_url;
NewsSource newsSource =null;
try {
String result = restTemplate.getForObject(URL, String.class);
//String jsonStr=getJsonString(result);
ObjectMapper mapper = new ObjectMapper();
// newsSource = mapper.readValue(result, NewsSource.class);
newsSource= (NewsSource) getJsonObject(result);
System.out.println("done:" +newsSource);
}catch (Exception ex){
System.out.println("oooh exception ");
}
return newsSource;
}
StackTrace
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token
at [Source: {"status":"ok","sources":[{"id":"abc-news-au","name":"ABC News (AU)","description":"Australia's most trusted source of local, national and world news. Comprehensive, independent, in-depth analysis, the latest business, sport, weather and more.","url":"http://www.abc.net.au/news","category":"general","language":"en","country":"au","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"al-jazeera-english","name":"Al Jazeera English","description":"News, analysis from the Middle East and worldwide, multimedia and interactives, opinions, documentaries, podcasts, long reads and broadcast schedule.","url":"http://www.aljazeera.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"ars-technica","name":"Ars Technica","description":"The PC enthusiast's resource. Power users and the tools they love, without computing religion.","url":"http://arstechnica.com","category":"technology","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"associated-press","name":"Associated Press","description":"The AP delivers in-depth coverage on the international, politics, lifestyle, business, and entertainment news.","url":"https://apnews.com/","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"bbc-news","name":"BBC News","description":"Use BBC News for up-to-the-minute news, breaking news, video, audio and feature stories. BBC News provides trusted World and UK news as well as local and regional perspectives. Also entertainment, business, science, technology and health news.","url":"http://www.bbc.co.uk/news","category":"general","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"bbc-sport","name":"BBC Sport","description":"The home of BBC Sport online. Includes live sports coverage, breaking news, results, video, audio and analysis on Football, F1, Cricket, Rugby Union, Rugby League, Golf, Tennis and all the main world sports, plus major events such as the Olympic Games.","url":"http://www.bbc.co.uk/sport","category":"sport","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"time","name":"Time","description":"Breaking news and analysis from TIME.com. Politics, world news, photos, video, tech reviews, health, science and entertainment news.","url":"http://time.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"usa-today","name":"USA Today","description":"Get the latest national, international, and political news at USATODAY.com.","url":"http://www.usatoday.com/news","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"}]}; line: 1, column: 402] (through reference chain: com.example.demo.dto.NewsSource["sources"]->java.util.ArrayList[0]->com.example.demo.dto.Source["sortBysAvailable"])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270)
at com.fasterxml.jackson.databind.DeserializationContext.reportMappingException(DeserializationContext.java:1234)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1122)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1075)
at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.handleNonArray(StringCollectionDeserializer.java:260)
at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.deserialize(StringCollectionDeserializer.java:187)
at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.deserialize(StringCollectionDeserializer.java:177)
at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.deserialize(StringCollectionDeserializer.java:20)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:276)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:287)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:259)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:276)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2858)
at com.example.demo.Utill.RuleUtill.getJsonObject(RuleUtill.java:80)
at com.example.demo.Utill.RuleUtill.getNewsSource(RuleUtill.java:100)
at com.example.demo.Service.NewsApiService.getSource(NewsApiService.java:32)
at com.example.demo.Controller.Home.somespecific(Home.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
json obj:===>null
done:null
最佳答案
由于某些原因,我对您的源代码进行了如下修改:
NewsSource
和 Source
中定义的指定 POJO。getJsonObject
是多余的。getNewsSource
中的异常处理未打印真正的原因。 获取新闻源
public NewsSource getNewsSource() {
String URL = source_url;
NewsSource newsSource =null;
try {
/*
String result = restTemplate.getForObject(URL, String.class);
ObjectMapper mapper = new ObjectMapper();
newsSource= (NewsSource) getJsonObject(result);
System.out.println("done:" +newsSource);
*/
newsSource = restTemplate.getForObject(URL, NewsSource.class);
System.out.println("done:" + newsSource.toString());
} catch (Exception ex){
System.out.println("oooh exception \n" + ex);
}
return newsSource;
}
希望这对您有帮助! :)
关于java - Jackson Mapper 返回 null 并带有 Spring 休息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47351684/
假设我有两个集合资源: /persons /organizations 一个 GET至 /persons/id/返回一个特定的人。同样,一个 GET至 /organizations/id返回一个特定的
这个问题在这里已经有了答案: Rest best practice: when to return 404 not found (1 个回答) 关闭 7 年前。 我有以下 API: api/gues
背景: 我正在尝试创建一个系统,允许用户对其他用户撰写的评论进行投票(类似于 Reddit)。用户可以选择三个投票值:-1、0 或 1。我创建了一个 POST API(使用 django Rest-f
我正在尝试使用休息调用,该调用获取操作系统中文件的位置。作为返回,其余调用模拟文件的下载。 下面是代码 Welcome to CoinPay Click on bel
我正在向后端发送一个文件,这是上传代码: export class FileUploadComponent { @Input() multiple: boolean = false; @Vie
字符串用户年龄; while(true){ System.out.println("Enter user Age"); userAge = scInput.ne
我正在使用堆栈进行括号检查。包含 break; 语句的 if else 语句之一导致段错误。 我尝试删除 break 程序运行正常但打印错误答案,因为需要 break 才能打印正确的输出。这种段错误的
我是新手,正在学习编程,但无法正确“中断”它。如果硬币不是 0、5、10 或 25,它应该“打破”(最后一个 if)。该程序应该像自动售货机一样工作,只使用 10 美分、5 分硬币、25 美分硬币,当
每次“打破”for-each 结构(PHP/Javascript)时,我都觉得很脏 所以像这样: //Javascript 示例 for (object in objectList) { if
对于这段代码: type Callback = (err: Error | null, result: String) => void; let apiThatAcceptsCallback = (c
如何获取 teamcity build 的变化?我得到以下 URL,其中列出了所有构建更改并提供了一个 URL,我们可以使用该 URL 查看更改 http://teamcityserver/httpA
社区 我正在寻找有关富文本的一些建议。目前的问题是:在后端(在数据库中)存储和管理富文本内容的最佳方式是什么。为什么这看起来像个问题,因为我们可以有多个平台:桌面、移动、网络,这会带来问题。 据我所知
我在向 html 返回错误时遇到问题。所以,我有带有“sql解释器”的网络应用程序。 HTML 在解释器中输入查询后,我在 javascript 中运行 POST 并拍摄到 sprin
我正在尝试为 Rest Controller 进行单元测试。我为经理对数据库访问做了一个 stub (~mock),它运行良好。我唯一的问题是,当我开始单元测试时,它不会启动应用程序。 如何从我的单元
我想使用 azure blob Rest api 创建文件夹,并且还想检查文件夹是否存在。 Hierarchy: arjun/images/ arjun/Videos/001.avi arjun/Vi
我正在寻找使用 django Rest 和 Angular 处理用户登录的最佳方法。目前我正在 Controller 中执行此操作, $http.post('accounts/login/', $sc
我想设计一个允许客户端上传图像的 API,然后应用程序创建图像的不同变体,例如调整大小或更改图像格式,最后应用程序将每个变体的图像信息存储在数据库中。当我尝试确定实现此任务的正确策略时出现问题,这里有
我无法使用 Angular Ajax 连接我的服务器 web2py Restful,但如果我在浏览器中设置 url,它就可以工作,但我不能在 Angular ajax =( Angular 链接
我想在我的项目中添加一个 rest api,因此我需要一个选择性的 mysql 语句 bt 我总是回来 { “错误”:“(1054,你\“'where子句'中的未知列'无'\”)” 代码有什么问题?我
我想为自己创建一个启动/停止 Azure VM 机器人。我想做的是拥有一个 slack/telegram 机器人,它可以监听消息并通过命令/start/stop 启动/停止我的虚拟机。我应该使用什么
我是一名优秀的程序员,十分优秀!