Tag Archives: json

[Solved] fastjson Error: com.alibaba.fastjson.JSONObject cannot be cast to xxxx

There is a StockData object. Normally, the JSON string to object should be:

StockData stockData = JSONObject.parseObject(str, StockData.class);

However, if the object is a generic (e.g. StockData<StockDetail>), it can be converted as above, but StockDetail throws an exception when it gets the object parameters via get com.alibaba.fastjson. JSONObject cannot be cast to cn.seagen.sorting.bean.StockDetail.

StockData<StockDetail> stockData = JSONObject.parseObject(str, StockData.class);

prompt JSONObject can not be converted to StockDetail object, the reason is probably.

fastjson conversion json object encounters a generic, it will not be correctly converted to a generic object, the converted object is a JSONObject object, not the object inside the generic, so there is also the above-thrown exception.

Solution

In addition to the above methods, fastjson also overloads a method.

public static <T> T parseObject(String text, TypeReference<T> type, Feature... features){}

Therefore, when the string is converted to a generic object, it is OK to use TypeReference for conversion. After conversion, StockDetail can normally get the parameter value of the object.

StockData<StockDetail> stockData = JSONObject.parseObject(str, new TypeReference<StockData<StockDetail>>(){});

[Solved] Failed toString() invocation on an object com.alibaba.fastjson.JSONException: write javaBean error

1. Recurrence problem

Today, when starting the spring boot project, the following problems suddenly occurred:

SLF4J: Failed toString() invocation on an object of type [com.superjson.superjsonmanager.config.jwt.JwtProperties$$EnhancerBySpringCGLIB$$3c58badf]
Reported exception:
com.alibaba.fastjson.JSONException: write javaBean error, fastjson version 1.2.70, class org.springframework.beans.factory.support.DefaultListableBeanFactory, fieldName : $$beanFactory, write javaBean error, fastjson version 1.2.70, class com.baomidou.mybatisplus.MybatisConfiguration, fieldName : configuration, write javaBean error, fastjson version 1.2.70, class com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceWrapper, fieldName : dataSource, write javaBean error, fastjson version 1.2.70, class com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl, fieldName : connection, write javaBean error, fastjson version 1.2.70, class com.mysql.cj.jdbc.ConnectionImpl, fieldName : connectionRaw, write javaBean error, fastjson version 1.2.70, class com.mysql.cj.jdbc.DatabaseMetaData, fieldName : metaData, write javaBean error, fastjson version 1.2.70, class com.mysql.cj.jdbc.result.ResultSetImpl, fieldName : catalogs
	at com.alibaba.fastjson.serializer.JavaBeanSerializer.write(JavaBeanSerializer.java:539)
	at com.alibaba.fastjson.serializer.JavaBeanSerializer.write(JavaBeanSerializer.java:149)
	at com.alibaba.fastjson.serializer.JSONSerializer.writeWithFieldName(JSONSerializer.java:333)
	at com.alibaba.fastjson.serializer.ASMSerializer_1_JwtProperties$$EnhancerBySpringCGLIB$$3c58badf.write(Unknown Source)
	at com.alibaba.fastjson.serializer.JSONSerializer.write(JSONSerializer.java:285)
	at com.alibaba.fastjson.JSON.toJSONString(JSON.java:758)
	at com.alibaba.fastjson.JSON.toJSONString(JSON.java:696)
	at com.alibaba.fastjson.JSON.toJSONString(JSON.java:661)
	at com.superjson.superjsonmanager.config.jwt.JwtProperties.toString(JwtProperties.java:73)
	at org.slf4j.helpers.MessageFormatter.safeObjectAppend(MessageFormatter.java:277)
	at org.slf4j.helpers.MessageFormatter.deeplyAppendParameter(MessageFormatter.java:249)
	at org.slf4j.helpers.MessageFormatter.arrayFormat(MessageFormatter.java:211)
	at org.slf4j.helpers.MessageFormatter.arrayFormat(MessageFormatter.java:161)
	at ch.qos.logback.classic.spi.LoggingEvent.getFormattedMessage(LoggingEvent.java:293)
	at ch.qos.logback.classic.spi.LoggingEvent.prepareForDeferredProcessing(LoggingEvent.java:206)
	at ch.qos.logback.core.OutputStreamAppender.subAppend(OutputStreamAppender.java:223)
	at ch.qos.logback.core.OutputStreamAppender.append(OutputStreamAppender.java:102)
	at ch.qos.logback.core.UnsynchronizedAppenderBase.doAppend(UnsynchronizedAppenderBase.java:84)
	at ch.qos.logback.core.spi.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:51)
	at ch.qos.logback.classic.Logger.appendLoopOnAppenders(Logger.java:270)
	at ch.qos.logback.classic.Logger.callAppenders(Logger.java:257)
	at ch.qos.logback.classic.Logger.buildLoggingEventAndAppend(Logger.java:421)
	at ch.qos.logback.classic.Logger.filterAndLog_1(Logger.java:398)
	at ch.qos.logback.classic.Logger.info(Logger.java:583)
	at com.superjson.superjsonmanager.SuperJsonManagerApplication.main(SuperJsonManagerApplication.java:51)
Caused by: com.alibaba.fastjson.JSONException: write javaBean error, fastjson version 1.2.70, class com.baomidou.mybatisplus.MybatisConfiguration, fieldName : configuration, write javaBean error, fastjson version 1.2.70, class com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceWrapper, fieldName : dataSource, write javaBean error, fastjson version 1.2.70, class com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl, fieldName : connection, write javaBean error, fastjson version 1.2.70, class com.mysql.cj.jdbc.ConnectionImpl, fieldName : connectionRaw, write javaBean error, fastjson version 1.2.70, class com.mysql.cj.jdbc.DatabaseMetaData, fieldName : metaData, write javaBean error, fastjson version 1.2.70, class com.mysql.cj.jdbc.result.ResultSetImpl, fieldName : catalogs
	at com.alibaba.fastjson.serializer.JavaBeanSerializer.write(JavaBeanSerializer.java:539)
	at com.alibaba.fastjson.serializer.JavaBeanSerializer.write(JavaBeanSerializer.java:149)
	at com.alibaba.fastjson.serializer.JSONSerializer.writeWithFieldName(JSONSerializer.java:333)
	at com.alibaba.fastjson.serializer.ASMSerializer_105_DefaultSqlSessionFactory.write(Unknown Source)
	at com.alibaba.fastjson.serializer.MapSerializer.write(MapSerializer.java:271)
	at com.alibaba.fastjson.serializer.MapSerializer.write(MapSerializer.java:44)
	at com.alibaba.fastjson.serializer.FieldSerializer.writeValue(FieldSerializer.java:320)
	at com.alibaba.fastjson.serializer.JavaBeanSerializer.write(JavaBeanSerializer.java:470)
	... 24 more

 

2. Analyze problems

I use alibaba.fastjson  to parses the jwtproperties object and reports the above error. This object is used to store the parameters of JWT, as shown in the following code:

/**
 * @author zby
 * @datetime 2022/8/19 12:05
 * @desc jwt entity class, get the configured properties from the yml configuration file
 */
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "jwt")
public class JwtProperties {

    @Value("${jwt.secret}")
    private String appSecret;

    @Value("${jwt.expiration}")
    private long expiration;

    @Value("${jwt.typ}")
    private String typ;

    @Value("${jwt.alg}")
    private String alg;

    @Value("${jwt.subject}")
    private String subject;

    @Value("${jwt.tokenStartWith}")
    private String tokenStartWith;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    public String getTokenStartWith() {
        return tokenStartWith + " ";
    }

    @Override
    @JSONField(serialize = false)
    public String toString() {
        return JSONObject.toJSONString(this);
    }
}

That is, rewrite the tostring() method internal statement JSONObject.toJSONString(this); has a problem, so the breakpoint is to see why this problem occurs, as shown in the screenshot below:

You will find that the dynamically generated the object of jwtproperties does not only have its property value, but also has many more property values that I have not defined. Why does this happen?

It should be that spring boot uses the dynamic proxy mode to instantiate the object, and this additional attribute value is the attribute value of the dynamic proxy object. Therefore, fastjson cannot resolve the attribute value of the dynamic proxy, so an error is reported.

3. Solve problems

Since we know that the error is caused by the spring boot dynamic agent, we do not give the object to the spring boot dynamic agent. We can modify the toString() method as follows:

@Override
@JSONField(serialize = false)
public String toString() {
  JSONObject jsonObject = new JSONObject();
  jsonObject.put("appSecret", this.appSecret);
  jsonObject.put("expiration", this.expiration);
  jsonObject.put("typ", this.typ);
  jsonObject.put("alg", this.alg);
  jsonObject.put("subject", this.subject);
  jsonObject.put("tokenStartWith", this.tokenStartWith);
  jsonObject.put("tokenHeader", this.tokenHeader);
  return JSONObject.toJSONString(jsonObject);
}

Start spring boot as shown in the following figure:

How to Solve SSM JSON Chinese Messy Code Issue

Solution:

Add the configuration <mvc:message-converters register-defaults=“true”> in mvc:annotation-driven of sprinmvc-servlet.xml.

The codes are as below:

Unified solution to json Chinese messy code problem<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--springmvc 统一解决json中文乱码问题-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

[Solved] SyntaxError: Unexpected end of JSON input

Note: When doing a project, I encountered the need to transfer a line of data objects to another page, using JSON.stringify => JSON.parse and then transferring it by url:

Then the error is reported as follows:

Later, after reviewing the relevant information, we found that we need to add a coding and decoding process, as follows:

After printing, the object appears:

Cause analysis:

Reason: If an address is encountered in the parameters of the object or the elements of the array, and the address includes ? and & these special symbols, the object/array must first be converted to a string by JSON.stringify and then encoded by encodeURIComponent, when received, first decoded by decodeURIComponent and then converted to JSON format object/array by JSON.parse

[Solved] SpringBoot Date Convert Error: JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime`

1. When data of type localdate in Java is tested on swagger, the format when input in the format of json is 2018-07-09. It should be noted that 07 and 09 are two digits, not one digit.

2. If the date is of LocalDate type, JacksonAutoConfiguration will automatically process whether the foreground transmits the date in string format to the background or the background returns the date in format to the front end.

3. If the date is of LocalDateTime type, we need to process it from the front end to the back end and from the back end to the front end. Because the configuration in the following YML does not apply to Java 8 date types, such as LocalDate and LocalDateTime, it only applies to fields of date or DateTime type.

#Date Formatting
spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss

Solution: add LocalDateTimeConfig configuration class

/**
 * LocalDateTime
 */
@Configuration
public class LocalDateTimeGlobalConfig {
    private static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     *Configuring LocalDateTime type serialization and deserialization
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
        /*return new Jackson2ObjectMapperBuilderCustomizer() {
            @Override
            public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
                jacksonObjectMapperBuilder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_PATTERN)));
                jacksonObjectMapperBuilder.deserializers(new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_PATTERN)));
            }
        };*/
        //This approach is equivalent to the above
        return builder -> {
            builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_PATTERN)));
            builder.deserializers(new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_PATTERN)));
        };
    }
}

How to Solve Converting circular structure to JSON‘ Error

‘Converting circular structure to JSON‘ error

Problem Description: the project needs to transfer strings to the background, so the object needs to be converted,
but JSON is used There is a bug of circular reference in the object during stringify (data) conversion, and we can’t find out where the copy is wrong.

The plug-in CircularJSON is used here to ignore circular references and force conversion

// install
npm install -S circular-json    
// import
import CircularJSON from 'circular-json'
// conversion
let data= CircularJSON.stringify(data)
let data= CircularJSON.parse(data)

[Solved] JSON.parse() Error: Unexpected end of JSON input

Error returned during JSON.parse() conversion due to conversion characters or other special characters in the data of the converted JSON.stringify().

Solution:

encoding before the JSON.stringify() transformation and decoding the operation when JSON.parse() is solved.

Example:

Jump pass parameter

 toEdit() {
    this.data.userInfo.faceData = this.data.faceData
    let info = encodeURIComponent(JSON.stringify(this.data.userInfo))
    wx.navigateTo({
      url: '../userEdit/userEdit?info=' + info 
    })
  },

receive data

onLoad(options) {
	//decodeURIComponent decoding
   let info = JSON.parse(decodeURIComponent(options.info))
   this.setData({info:info})
}

[Solved] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

INSERT INTO report(NAME,keyword,refile,content,DATE,STATUS) VALUES ('%s','%s','%s','%s','%s',0)%("name", "key", "refile", "content",str(datetime.now()))

report errors

ERROR CODE: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key,refile,content,date,status) VALUES ('%s','%s','%s','%s','%s',0)%("name", "ke' at line 1

The keyword of MySQL is used. After modification

    sql="INSERT INTO report(`name`,`keyword`,`refile`,`content`,`date`,`status`) VALUES ('%s','%s','%s','%s','%s',0)"%(name,key, refile, content,str(datetime.now()))

[Solved] Heroku Error: Web process failed to bind to $PORT within 60 seconds of launch

Error description

If the set port number is less than 1000, an error will be reported, and there is no permission

2022-03-29T10:23:16.651636+00:00 heroku[web.1]: State changed from crashed to starting
2022-03-29T10:23:28.994173+00:00 heroku[web.1]: Starting process with command `python /code/server3.py`
2022-03-29T10:23:30.091143+00:00 app[web.1]: Traceback (most recent call last):
2022-03-29T10:23:30.091204+00:00 app[web.1]: File "/code/server3.py", line 247, in <module>
2022-03-29T10:23:30.091205+00:00 app[web.1]: serverSocket.bind(("127.0.0.1", serverPort))
2022-03-29T10:23:30.091208+00:00 app[web.1]: PermissionError: [Errno 13] Permission denied
2022-03-29T10:23:30.234919+00:00 heroku[web.1]: Process exited with status 1
2022-03-29T10:23:30.279569+00:00 heroku[web.1]: State changed from starting to crashed

If you set the port number to 8080, you will not be connected within 60 seconds

2022-03-29T10:53:34.400924+00:00 heroku[web.1]: State changed from crashed to starting
2022-03-29T10:53:49.432473+00:00 heroku[web.1]: Starting process with command `python /code/server3.py`
2022-03-29T10:53:33.432308+00:00 app[api]: Release v9 created by user ***@icloud.com
2022-03-29T10:53:33.432308+00:00 app[api]: Deployed web (350d1bd5740a) by user ***@icloud.com
2022-03-29T10:54:49.500818+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2022-03-29T10:54:49.587777+00:00 heroku[web.1]: Stopping process with SIGKILL
2022-03-29T10:54:49.800462+00:00 heroku[web.1]: Process exited with status 137

If the port number in the environment variable is referenced dynamically, the acquisition fails

2022-03-29T11:12:03.984493+00:00 heroku[web.1]: State changed from crashed to starting
2022-03-29T11:12:19.984320+00:00 heroku[web.1]: Starting process with command `python /code/server3.py`
2022-03-29T11:12:21.706887+00:00 heroku[web.1]: Process exited with status 1
2022-03-29T11:12:21.536737+00:00 app[web.1]: Traceback (most recent call last):
2022-03-29T11:12:21.536756+00:00 app[web.1]: File "/code/server3.py", line 248, in <module>
2022-03-29T11:12:21.536757+00:00 app[web.1]: serverSocket.bind(("0.0.0.0", serverPort))
2022-03-29T11:12:21.536757+00:00 app[web.1]: TypeError: an integer is required (got type NoneType)
2022-03-29T11:12:21.769096+00:00 heroku[web.1]: State changed from starting to crashed

No matter the local address is not written,
ServerSocket Bind ((“”, serverport))
or 127.0.0.1
ServerSocket Bind ((“127.0.0.1”, serverport))
or write 0.0.0
ServerSocket Bind ((“0.0.0.0”, serverport))
doesn’t work

 

Solution (Python Project):

Dynamic binding port number is required

To write this in dockerfile, pass in $post

#Base image based on
FROM python:3.4

#code added to code folder
ADD . /pythonProject /code

# Set the code folder to be the working directory
WORKDIR /code

# Install support
#RUN pip install -r requirements.txt

CMD python /code/server3.py $PORT

Python file writing format,  obtain through parameters in server.py

serverPort = int(sys.argv[1])

The complete structure is as follows

if __name__ == '__main__':
    serverSocket = socket(AF_INET, SOCK_STREAM)
    serverPort = int(sys.argv[1])
    serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    serverSocket.bind(("", serverPort))

    serverSocket.listen(5)
    print('The server is running')
    # Main web server loop. It simply accepts TCP connections, and get the request processed in seperate threads.
    while True:
        # Set up a new connection from the client
        connectionSocket, addr = serverSocket.accept()
        # Clients timeout after 60 seconds of inactivity and must reconnect.
        connectionSocket.settimeout(600)
        # start new thread to handle incoming request
        _thread.start_new_thread(process, (connectionSocket,))

Solution (Nodejs Project):

// production
config.port = process.env.PORT

app.listen(config.port, () => {
  logger.info('Listening on port %d', config.port);
});

or

.listen(process.env.PORT || 5000)

or

production: {
    server: {
        host: '0.0.0.0',
        port: process.env.PORT
    }
}

IDEA: How to Solve Springboot Project install Error

Found multiple occurrences of org.json.JSONObject on the class path:

    jar:file:/C:/Users/Administrator/.m2/repository/org/json/json/20160810/json-20160810.jar!/org/json/JSONObject.class
    jar:file:/C:/Users/Administrator/.m2/repository/com/vaadin/external/google/android-json/0.0.20131108.vaadin1/android-json-0.0.20131108.vaadin1.jar!/org/json/JSONObject.class

You may wish to exclude one of them to ensure predictable runtime behavior

Solution:

Add to pomz: com.vaadin.external.google dependency ignore can be

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.vaadin.external.google</groupId>
					<artifactId>android-json</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

Python parsing JSON Error: NameError: name ‘false’ is not defined

Python parses a JSON string and directly calls JSON.Loads error:

NameError: name 'false' is not defined

Solution:
use Python’s raw strings, that is, add R'''before the JSON string, and then add '' '. For example:

>>> import json
>>> json_string = r'''{"created_at":"Thu Jul 10 20:02:00 +0000 2014","id":487325888950710272,"id_str":"487325888950710272","text":"\u5f81\u9678\u300c\u5de6\u8155\u306e\u7fa9\u624b\u306f\u30db\u30ed\u3060\u300d","source":"\u003ca href=\"http:\/\/twittbot.net\/\" rel=\"nofollow\"\u003etwittbot.net\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":1429838018,"id_str":"1429838018","name":"\u3053\u3093\u306a\uff30\uff30\u306f\u5acc\u3060\u3002","screen_name":"iyada_pp","location":"\u516c\u5b89\u5c40\u306e\u3069\u3053\u304b\u3002","url":null,"description":"\u3010\u3053\u3093\u306aPSYCHO-PASS\u306f\u5acc\u3060\u306a\u3011\u3068\u3044\u3046\u304f\u3060\u3089\u306a\u3044\u5984\u60f3bot\u3067\u3059\u3002\u30ad\u30e3\u30e9\u5d29\u58ca\u304c\u6fc0\u3057\u3044\u306e\u3067\u3054\u6ce8\u610f\u304f\u3060\u3055\u3044\u3002","protected":false,"followers_count":99,"friends_count":98,"listed_count":5,"created_at":"Wed May 15 07:52:33 +0000 2013","favourites_count":0,"utc_offset":null,"time_zone":null,"geo_enabled":false,"verified":false,"statuses_count":12584,"lang":"ja","contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/3661872276\/ab7201283dac5dc1789bb6dfa9b6abe4_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/3661872276\/ab7201283dac5dc1789bb6dfa9b6abe4_normal.jpeg","profile_link_color":"0084B4","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"symbols":[],"urls":[],"user_mentions":[]},"favorited":false,"retweeted":false,"filter_level":"medium","lang":"ja"}'''
>>> json.loads(json_string)