Author Archives: Robins

JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token

The problem
After the front end passes JSON format data to the back end, SpringMVC reports

org.springframework.http.converter.HttpMessageNotReadableException:
     * JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token;
     * nested exception is com.fasterxml.jackson.databind.JsonMappingException:
     * Can not deserialize instance of java.lang.String out of START_OBJECT token
     *  at [Source: java.io.PushbackInputStream@6822f8aa; line: 1, column: 88] (through reference chain: com.xxx.XXXDto["employees"])

plan
To solve this problem, we can use one of the Uniform Exception Handling methods in Spring

@ExceptionHandler({HttpMessageNotReadableException.class, JsonMappingException.class, HttpMediaTypeNotSupportedException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String,Object> exceptionHandler(Exception ex){
        Map<String,Object> map = new HashMap<>(3);
        try{
           map.put("code","400");
           map.put("msg",ex.getMessage());
           return map;
        }catch (Exception e){
            log.error("exception handler error",e);
            map.put("code","400");
            map.put("msg",e.getMessage());
            return map;
        }
    }

Solve problems encountered in the process
The above method can handle the problem of JSON formatting errors, but the data content returned to the front end is in the following format

JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token;  nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token  at [Source: java.io.PushbackInputStream@6822f8aa; line: 1, column: 88] (through reference chain: com.xxx.XXXDto["callBackUrl"])

We can’t see what the problem is at first sight, and even if we are familiar with the error, we can’t immediately find out where the problem is, because we need to process the above data and then send it back to the front end. Right
Finally solve the problem
We debug the source code found, Change is abnormal in springframework org. Springframework. HTTP. Converter. Json. AbstractJackson2HttpMessageConverter
thrown inside abnormal is
JsonMappingException extends JsonProcessingException
, Thrown in for springmvc HttpMessageNotReadableException, as a result, we only need to add corresponding processing logic unified exception handling, can be returned to the front

@ExceptionHandler({HttpMessageNotReadableException.class, JsonMappingException.class, HttpMediaTypeNotSupportedException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String,Object> exceptionHandler(Exception ex){
        Map<String,Object> map = new HashMap<>(3);
        try{
            if(ex instanceof HttpMessageNotReadableException
                    && ex.getMessage().indexOf("JSON parse error:")>-1){
                map.put("code","400");
                String message=ex.getMessage();
                int beginIndex=message.indexOf("XXXDto[\"");
                int endIndex=message.indexOf("\"])",beginIndex);
                message="parameter"+message.substring(beginIndex+22,endIndex)+" format error";
                map.put("msg",message);
            }else{
                map.put("code","400");
                map.put("msg",ex.getMessage());
            }
            return map;
        }catch (Exception e){
            log.error("exception handler error",e);
            map.put("code","400");
            map.put("msg",e.getMessage());
            return map;
        }
    }

Error resolution: request execution error. Endpoint = defaultendpoint {serviceurl=‘ http://127.0.0.1 :6668/eureka/}

>
1, confirm the defaultZone wording, yml configuration file named here requires the use of the hump, some people all lowercase, also quote the wrong
2, yml file should not read the configure port 6668, can be the 6668 server and client are replaced by the default of 8761, restart again, no error after the switch back to 6668, restart without error
3, yml file format, strictly abide by the following; If there is any Chinese in the file, make sure the Chinese is UTF-8

Jsoneexception: a jsonobject text must begin with ‘{at character 0


 
JSONException: A JSONObject text must begin with ‘{‘ at character 0
 
You can cache HTTP in HTTPS

 
 
Welcome to pay attention to the public number, receive a variety of free learning videos, learn the relevant Java various technical points interview knowledge, there are relevant learning questions or interview confusion, you can also through the public number private letter bloggers

 

JSON data format net.sf.json .JSONException: A JSONObject text must begin with ‘{‘ at character 1 of Error:(f…

The substring (3) the use of the http://www.w3school.com.cn/jsref/jsref_substring.asp

Possibility 1: if sb is the data to be converted, let’s say sb is a String

 


The char
The STR [] = sb. ToString (). ToCharArray ();


for
(
The int
i=
0
; i< str.length; i++){


System.out.println(str[i]);


}

After can get into an array of form, check the array before any Spaces, such as if useful
sb.toString().trim().substring(
1
); Cut off


The String json = sb. ToString (). The trim (). The substring (
1
);


The // String json = "{\" success \ ": true, \" MSG \ ": \ \" successful "} ";


System.out.println(json);


System.out.println(json.length());


The JSONObject JSONObject = JSONObject. FromObject (json. The trim ());


System.out.println(jsonobject);



The

"Result" : [{}] ------ left less {

Possibility 2: No initialization, no initBmob () is likely to report this wrong Unregistered

Possibility 3: There is an extra space before the data in the database

 

Reproduced in: https://www.cnblogs.com/wth21-1314/p/7381575.html

209151; org.json.JSONException A JSONObject text must begin with'{‘at character 1 of {

Cause analysis:
parse the json data, the format is not correct, is usually as a result of the returned json data outside a layer of more “” (double quotes)
if, as a string, plus @ ResponseBody annotation, then parsing json over there will more outside a layer of” ”
Solutions:

(1) if the string is converted to json, then you need to call the json packet method (string turn json object), and then forwards the json object resolution in the past.
2. If the entity object, you need to call the Json packet method (object turn Json object), and then forwards the Json object resolution in the past.
no matter what you need to turn the object data type, anyhow can not directly return to the past for Json parsing, need to convert a Json object before parsing.
Last word: it’s not easy to write. If you like it or find it helpful, remember to follow it or bookmark it

ansoft:Com Engine non-responsive since

Ansoft :Com Engine Non-responsive since 17:23:04, October 18, 2015.If Persisting for Long, Functional Testing kills the Com Engine Process and Restart Analysis.
When this situation occurs in Ansoft simulation, the progress bar is 0 and unchanged. Many methods have been tried on the Internet, but the software crashed and was closed and then opened, which can be simulated normally.

Activity of Android studio_ main.xml Unable to preview (gray page)

The activity_main.xml in Android Studio cannot be previewed (the gray page only displays the ActionBaroverLayout) and controls cannot be pulled into it. The styles.xml file is in the values file

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>

To change to the preview state, add “base.” before the Theme in the

[Jackson exception] com.fasterxml.jackson . databind.JsonMappingException Exception handling method

In the project, the parent layer is Car.java [Vehicle Entity] and the child layer is CarCommonParam.java [Vehicle Basic Entity], which is the basic information of a vehicle to multiple vehicles
But at the time of query library collection is a entity error: 【 com. Fasterxml. Jackson. Databind. JsonMappingException 】

com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: cn.skyable.zulin.common.bean.CarCommonParam_$$_jvst95e_39["handler"])
X-Zc-Ack-->null
	at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:59)
	at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:26)
	at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:541)
	at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:644)
	at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
	at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:114)
	at com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:1837)
	at com.fasterxml.jackson.core.base.GeneratorBase.writeObject(GeneratorBase.java:261)
	at com.ablecloud.cloudservice.ACObjectMarshaller.marshalArray(ACObjectMarshaller.java:53)
	at com.ablecloud.cloudservice.ACObjectMarshaller.marshalObject(ACObjectMarshaller.java:37)
	at com.ablecloud.cloudservice.ACObjectMarshaller.marshal(ACObjectMarshaller.java:22)
	at com.ablecloud.common.ACObject.toString(ACObject.java:415)
	at java.lang.String.valueOf(String.java:2994)
	at java.lang.StringBuilder.append(StringBuilder.java:131)
	at cn.skyable.zulin.BaseTest.dealResp(BaseTest.java:88)
	at cn.skyable.zulin.logistics.TestLogistics.TestlistCarsByLogId(TestLogistics.java:65)
	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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
	at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:539)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207)

Error description: A truncation is made in the entity where the child layer can look up information about the parent layer, but the parent layer cannot look up information about the child layer due to circular reference problem.
Solution:
Add to the parent car.java
Instead of

Just !!!!

JSON parse error: invalid UTF-8 solution series

Today, the code passed the local test and the Tomcat server was deployed. My front-end colleague gave me the following error feedback:

Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"JSON parse error: Invalid UTF-8 middle byte 0x3f

I immediately started the local project and asked colleagues in the front end to connect my local project for relevant function prompts. The result was that everything was normal without any problem, and the response error messages returned by checking the front end were all 400.
The error screenshot is not saved. The format of the error response is as follows:
To be added.
 
We must be clear here: in response to the 400 error code, there are several reasons for the error:
Tomcat service transport encoding format not specified (UTF-8)
Tomcat server JAR file encoding format not specified (UTF-8)
The front-end request header parameter does not match the backend parse header parameter.
Step 1: Configure the Tomcat server to transfer the encoding format specified:
Edit the tomcat/conf/server.xml file and add encoding attributes to the Connector tag: uriEncoding =”UTF-8″

Setjava_opts =%JAVA_OPTS% -dfile.encoding =UTF-8; setjava_opts % -dfile.encoding =UTF-8

SpringMVC backend code specifies request header information:

Exception jsonmappingexception: out of start_ ARRAY token

1 problem
When a new HTTP interface is called and the data is parsed, an exception is raised:
Under Caused by: com. Fasterxml. Jackson. Databind. JsonMappingException: Can not deserialize the instance of the com. Out of XXX START_ARRAY token
The second analysis
If you look at the JSON data for the data, it’s an array. The original one is encapsulated as response.
So, you can encapsulate. Modify parsing without encapsulation:

objectMapper.readValue(json,XXOjject[].class);

This is an array object that can be converted to a list and returned normally.

H5 page left and right stretch content area

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>resize</title>
</head>
<style>
  *,*:before,*:after{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
  }
  body{
    display: flex;
    flex-direction: column;
    align-items: stretch;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
  }
  header,footer{
    flex: none;
    width: 100%;
    height: 60px;
    background: lightgrey;
  }
  footer{
    position: relative;
    background: lightblue;
  }
  .main{
    flex: auto;
    display: flex;
    align-items: stretch;
  }
  .sidebar{
    flex: none;
    width: 200px;
    background: lightgoldenrodyellow;
  }
  .container{
    position: relative;
    flex: auto;
    background: #e0bfc4;
  }
  .resize{
    position: absolute;
    z-index: 100;
    touch-action: none;
  }
  .resize.horizontal{
    top: 0;
    bottom: 0;
    left: 0;
    width: 4px;
    cursor: e-resize;
  }
  .resize.vertical{
    left: 0;
    right: 0;
    top: 0;
    height: 4px;
    cursor: n-resize;
  }
</style>
<body>
  <header>Header</header>
  <section class="main">
    <acticle class="sidebar">Sidebar</acticle>
    <acticle class="container">Content
      <div class="resize horizontal" onmousedown="mousedown('horizontal')"></div>
    </acticle>
  </section>
  <footer>Bottom
    <div class="resize vertical" onmousedown="mousedown('vertical')"></div>
  </footer>
</body>
<script>

function mousedown(flag){
  document.onmousemove = function(){
    // console.log("flag",event,flag)
    if (flag === "horizontal"){
      if (event.x < 200 || event.x > 800) return
      var sidebar = document.querySelector(".sidebar")
      sidebar.style.width = event.x + "px"
    } else if(flag === "vertical"){
      if (event.y < 500 || event.y > 877) return
      var foot =  document.querySelector("footer")
      var top = Number(foot.getBoundingClientRect().top)
      var height = Number(foot.getBoundingClientRect().height)
      foot.style.height = height + top -event.y + "px"
    }
  }
}

document.onmouseup = function(){
  document.onmousemove = null
}

</script>
</html>