Tag Archives: json

Jackson localdatetime to string error: jsr310 [How to Solve]

error code

public static void main(String[] args)throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    final LocalDateTime localDateTime = LocalDateTime.now();
    final String s = objectMapper.writeValueAsString(localDateTime);
    System.out.println(s);
}

Error

reason

The date was not formatted during conversion

Solution:

public static void main(String[] args)throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    
        // Date and time formatting
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // Set the serialization format of LocalDateTime
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        objectMapper.registerModule(javaTimeModule);

    final LocalDateTime localDateTime = LocalDateTime.now();
    final String s = objectMapper.writeValueAsString(localDateTime);
    System.out.println(s);
}

Unknown SSL protocol error in connection to xxx:443 [How to Solve]

1. Unknown SSL protocol error in connection to XXX: 443

Unknown SSL protocol error in connection to XXX: 443 occurs when Git is used to download from a remote location..

Method 1:

(example):

Set up proxy server:

: Add in .gitconfig

http.proxy=127.0.0.1:8087

http.sslVerify=false

Method 2:

(example):

Type directly on the command line

git config --global http.proxy 127.0.0.1:8087

git config --global http.sslVerify false

[Solved] org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot

09:06:12.163 [http-nio-9207-exec-6] ERROR c.s.p.c.GlobalExceptionHandler - [exceptionHandler,90] - 发生其他异常,原因是;{}
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token
 at [Source: (PushbackInputStream); line: 1, column: 2] (through reference chain: java.lang.Object[][0])
	at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:285)
	at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:243)
	at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:205)
	at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:158)
	at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:131)
	at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
	at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
	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:53)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at com.signature.pc.config.HttpServletRequestReplacedFilter.doFilter(HttpServletRequestReplacedFilter.java:35)
	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:100)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	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.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:93)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	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:201)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	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:202)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
	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)
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.String` out of START_OBJECT token
 at [Source: (PushbackInputStream); line: 1, column: 2] (through reference chain: java.lang.Object[][0])
	at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59)
	at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468)
	at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242)
	at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1148)
	at com.fasterxml.jackson.databind.deser.std.StdDeserializer._parseString(StdDeserializer.java:615)
	at com.fasterxml.jackson.databind.deser.std.StringArrayDeserializer.deserialize(StringArrayDeserializer.java:157)
	at com.fasterxml.jackson.databind.deser.std.StringArrayDeserializer.deserialize(StringArrayDeserializer.java:21)
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3521)
	at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:274)
	... 58 common frames omitted

Interface input parameter format:

Front end parameter transfer format

[{"id":"26a0eac8-edb1-43be-9869-4f7c45c0693a"},
{"id":"E3ECF542585749B996EC0C13907E7D94"}]

.
.
.
the problem is obvious. The format of the value passed by the front end is incorrect. What we need is an array of string type, while the data passed by the front end is object type data.

The front-end transmission parameter is changed to:

[
    "30lkbc2b-1c80-46c3-857e-e934e9842c08",
    "E3ECF542585749B996EC0C13907E7D94"
]

That’s it

Syntaxerror: unexpected end of JSON input [How to Solve]

Onload executes only once
SetData stores data in the page cache
if the data is undefined, you may need that = this. After the curly braces, the of these changes
e in the event function is an event, which refers to the event of this operation
options are objects.

If it is written like this, an error will be reported: syntax error: unexpected end of JSON input

At this time, do not use the arrow function!

So there is no error!

After configuring the ES password, logstash starts with error 401?

This problem occurs because after elasticsearch configures the password, the connection es encounters authentication problems when logstash starts. The solution requires configuring the account password in the logstash configuration file

vim /app/logstash/config/beat_es.conf

input {
   beats {
     port => 5044
   }
}
filter {
    #Only do json parsing on nginx json logs, system messages are in other formats, no need to handle
    if [fields][log_type] == "nginx"{
      json {
         source => "message"
         remove_field => ["beat","offset","tags","prospector"] #Remove fields, no collection required
      }
      date {
        match => ["timestamp", "dd/MMM/yyyy:HH:mm:ss Z"] # match the timestamp field
        target => "@timestamp" # write the matched data to the @timestamp field
      }
  }
}
 
output {

       if [fields][log_type] == "ruoyi" {
         elasticsearch {
            hosts => ["node1:9200","node2:9200"]
            user => elastic
            password => "123123"
            index => "ruoyi_log"
            timeout => 300
        }
       }
}

[Solved] JSON parse error: Cannot deserialize instance of `java.util.ArrayList<..> out of START_OBJECT token;

JSON parse error: Cannot deserialize instance of java.util.ArrayList<com.sangfor.ngsoc.knowledge.to.UserEntity> out of START_OBJECT token;
1. problem replication
① First, configure both knowledge and auth services into eureka.

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

② The project path of auth service is:

server:
  port: 8081
  servlet.context-path: /ngso/AUTH/

③ Interface of remote auth service:

@Api(tags = "Usersheet")
@Slf4j
@Validated
@RestController
@ResponseResult
@RequestMapping("/api/v2")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/users/inner/exact")
    public PageData<UserEntity> exactPageQueryUserList(@Validated @RequestBody UserQo userQo,
                                                       @RequestParam(SessionKey.DOMAIN_ID) String domainId) {
        userQo.setDomainId(domainId);
        return userService.exactPageQueryUserList(userQo);
    }
}

④ Feign interface of knowledge service, calling the interface of remote auth service:

@FeignClient(name = "AUTH")
public interface AuthFeignService {
    @PostMapping("/ngso/AUTH/api/v2/users/inner/exact")
    PageData<UserResp> exactPageQueryUserList(
            @RequestBody UserReqDto userReqDto,
            @RequestParam(SessionKey.DOMAIN_ID) String domainId);
}

(5) calling feign interface in knowledge service:

@Override
public String addDoc() {
    List<String> userIds = new ArrayList<>();
     UserInfo userInfo = UserInfoShareHolder.getUserInfo();
    userIds.add(userInfo.getId());
    UserReqDto userReqDto = new UserReqDto(userIds);
    userReqDto.setPageNum(1);
    userReqDto.setPageSize(1);
    PageData<UserResp> pageDataApiResponse = authFeignService
        .exactPageQueryUserList(userReqDto, UserInfoShareHolder.getUserInfo().getDomainId());
}

Result error:

JSON parse error: Cannot deserialize instance of `java.util.ArrayList<com.sangfor.ngsoc.knowledge.to.UserEntity>` out of START_OBJECT token; 

2. Solutions

① First, directly call the auth service interface without using the remote service: localhost: 8081/NGSO/auth/API/V2/users/inner/exact

There are more code and message messages than the actual response data, indicating that the response data is encapsulated

{
    "code": 0,
    "message": "成功",
    "data": {
        "pageNum": 1,
        "pageSize": 1,
        "totalCount": 1,
        "data": [
            {
                "id": "fx-user-fec844b9e0dc0d80000004",
                "name": "sysadmin",
                "phone": "",
                "email": "",
                "description": "Built-in user: default platform system administrator account",
                "domainId": "fx-domain-fec833bfa0dbcc40000001",
                "projectId": " ",
                "enabled": 1,
                "createTime": "2021-10-18 15:41:17",
                "updateTime": "2021-10-21 16:35:11",
                "changeTime": "2021-10-18 16:44:37",
                "loginTime": "2021-10-21 16:35:11",
                "options": 0,
                "builtIn": 1
            }
        ]
    }
}

② View the code and add a layer of encapsulation:

@FeignClient(name = "AUTH" )
public interface AuthFeignService {
   @PostMapping("/ngso/AUTH/api/v2/users/inner/exact")
    ApiResponse<PageData<UserResp>> exactPageQueryUserList(
            @RequestBody UserReqDto userReqDto,
            @RequestParam(SessionKey.DOMAIN_ID) String domainId);
}

Could not write JSON: write javaBean error, fastjson version x.x.x, class

Could not write JSON: write javaBean error, fastjson version x.x.x, class

Possible causes of error reporting (welcome to add)

1. Serialization problem. The reason is that some fields in the bean object cannot be serialized. For example, fields of multipart type cannot be serialized. You can not serialize annotations through @ jsonfailed (serialize = false)

2. When converting JSON to object, there are some syntax problems in the attribute get/set, such as null pointer, type conversion, divisor and dividend in division are 0, etc

3. Syntax problem in get/set when database query returns (as above)

[Solved] VS Code Error: Vetur can‘t find ‘tsconfig.json‘ or ‘jsconfig.json‘

1. Cause

A new configuration file of vetur.config.js is added in vetur 0.31.0.
after this version, priority will be given to finding whether the project is equipped with tsconfig.json (TS project) or jsconfig.json (JS project).
if these two files are not found, go to vetur.config.js. If they are not found, this prompt will be thrown.

2. Explain

The JavaScript support of vscode can run in two different modes:
file range (without jsconfig.JSON)
in this mode, JavaScript files opened in vscode are regarded as independent units
as long as the file A.js does not explicitly reference the file b.ts (using// reference instructions or commonjs modules), there is no common project context between the two files.

3. Explicit project

(use jsconfig.JSON)

The JavaScript project is defined through the jsconfig.JSON file. The existence of such a file in the directory indicates that the directory is the root directory of the JavaScript project
the file itself can optionally list files belonging to the project, files to be excluded from the project, and compiler options (see below)
the JavaScript experience improves when you have a jsconfig.json file in your workspace that defines the project context
therefore, when you open a JavaScript file in a new workspace, we provide a prompt to create a jsconfig.json file.

4. Solution (1 out of 3)

4.1. Configure the vehicle plug-in and ignore the prompt </ H6>
 "vetur.ignoreProjectWarning": true,

4.2. Create jsconfig.json file in the project root directory </ H6>

Add code:

{
    "include": [
        "./src/*"
    ]
}
4.3. Create the vetur.config.js file in the project root directory </ H6>

Add code:

module.exports = {
    // vetur configuration, which will override the settings in vscode.  default: `{}`
    settings: {
        "vetur.useWorkspaceDependencies": true,
        "vetur.experimental.templateInterpolationService": true
    },
    // Normal projects use the default configuration default: `[{ root: './' }]`
}

Object of type timestamp is not JSON serializable

First of all, the reason for the error is the datetime type field when exporting JSON.

Added in the code:
class dateencoder (JSON. Jsoneencoder):
Default (self, obj):
if isinstance (obj, datetime. Datetime):
return obj.strftime (“% Y -% m -% DT% H:% m:% s”)
else:
return json.jsoneencoder.default (self, obj)

Then add a CLS = dateencoder
in json.dump to solve the problem

As shown in the figure:


no error will be reported

[Solved] Parsing JSON error unexpected end of JSON input

It’s normal to jump and pass parameters using JSON, but today I don’t know why I reported an error, unexpected end of JSON input,
reason
I found the answer on the Internet because there are unrecognized contents in the passed parameters, and the parameters I passed contain rich text, Therefore, there is no resolution
solution
start with JSON character parameters (parent page) on the page to jump to

issueanswer(item){
				let arrar = JSON.stringify(item)
				uni.navigateTo({
					url:"issueanswer?arr="+encodeURIComponent(arrar)
				})
			},

Then accept and parse the parameters in onload of the sub page

onLoad(option) {
			this.arr =JSON.parse(decodeURIComponent(option.arr))
		},