kandi background
Explore Kits

fastjson | A fast JSON parser/generator for Java | JSON Processing library

 by   alibaba Java Version: 1.2.79 License: Apache-2.0

 by   alibaba Java Version: 1.2.79 License: Apache-2.0

Download this library from

kandi X-RAY | fastjson Summary

fastjson is a Java library typically used in Utilities, JSON Processing applications. fastjson has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can download it from GitHub, Maven.
[![Java CI](https://github.com/alibaba/fastjson/actions/workflows/ci.yaml/badge.svg?branch=master)](https://github.com/alibaba/fastjson/actions/workflows/ci.yaml) [![Codecov](https://codecov.io/gh/alibaba/fastjson/branch/master/graph/badge.svg)](https://codecov.io/gh/alibaba/fastjson/branch/master) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.alibaba/fastjson/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.alibaba/fastjson/) [![GitHub release](https://img.shields.io/github/release/alibaba/fastjson.svg)](https://github.com/alibaba/fastjson/releases) [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready—​to—​Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/alibaba/fastjson) [![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/fastjson2.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:fastjson2).
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • fastjson has a highly active ecosystem.
  • It has 24265 star(s) with 6431 fork(s). There are 1340 watchers for this library.
  • There were 1 major release(s) in the last 12 months.
  • There are 1683 open issues and 1576 have been closed. On average issues are closed in 119 days. There are 136 open pull requests and 0 closed requests.
  • It has a positive sentiment in the developer community.
  • The latest version of fastjson is 1.2.79
fastjson Support
Best in #JSON Processing
Average in #JSON Processing
fastjson Support
Best in #JSON Processing
Average in #JSON Processing

quality kandi Quality

  • fastjson has 0 bugs and 0 code smells.
fastjson Quality
Best in #JSON Processing
Average in #JSON Processing
fastjson Quality
Best in #JSON Processing
Average in #JSON Processing

securitySecurity

  • fastjson has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • fastjson code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
fastjson Security
Best in #JSON Processing
Average in #JSON Processing
fastjson Security
Best in #JSON Processing
Average in #JSON Processing

license License

  • fastjson is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
fastjson License
Best in #JSON Processing
Average in #JSON Processing
fastjson License
Best in #JSON Processing
Average in #JSON Processing

buildReuse

  • fastjson releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • fastjson saves you 177099 person hours of effort in developing the same functionality from scratch.
  • It has 181091 lines of code, 19450 functions and 3015 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
fastjson Reuse
Best in #JSON Processing
Average in #JSON Processing
fastjson Reuse
Best in #JSON Processing
Average in #JSON Processing
Top functions reviewed by kandi - BETA

kandi has reviewed fastjson and discovered the below as its top functions. This is intended to give you an instant insight into fastjson implemented functionality, and help decide if they suit your requirements.

  • Build JavaBeanInfo from given class .
  • Deserialize field information .
  • Scan a date in ISO8601 format .
  • Gets an object writer .
  • Write a string with double quotes .
  • Generate write as array .
  • tokenize object
  • Scan a field name .
  • Get the value of a property
  • Writes the value of the property .

fastjson Key Features

[Documentation Home](https://github.com/alibaba/fastjson/wiki)

[Contributing Code](https://github.com/nschaffner/fastjson/blob/master/CONTRIBUTING.md)

[Frequently Asked Questions](https://github.com/alibaba/fastjson/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98)

[maven][1]

[the latest JAR][2]

default

copy iconCopydownload iconDownload
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.76</version>
</dependency>

SpringBoot: Validation without @Valid annotation

copy iconCopydownload iconDownload
public abstract class GenericService<T> {

    protected Validator validator;

    protected void validateDomainRecord(T object, String message) {
        Set<ConstraintViolation<T>> violations = validator.validate(object);
        if(!violations.isEmpty()) {
            throw new ConstraintViolationException(message, violations);
        }
    }
}
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import lombok.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

@Component
@Slf4j
public class MyCustomWebSocketHandler extends AbstractWebSocketHandler {

    private Validator validator;
    
    @Override
    protected void handleTextMessage(@NonNull WebSocketSession session, @NonNull TextMessage message) {
        CustomMessage customMessage = JSON.parseObject(message.getPayload(), CustomMessage.class);
        // Validate the message according to javax.validation annotations and throw MethodArgumentNotValidException if invalid
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();            
        Set<ConstraintViolation<CustomMessage>> violations = validator.validate(customMessage);
        if(!violations.isEmpty()) {
            throw new ConstraintViolationException(message, violations);
        }

        log.debug("Received valid message {}", customMessage)
    }
}
-----------------------
public abstract class GenericService<T> {

    protected Validator validator;

    protected void validateDomainRecord(T object, String message) {
        Set<ConstraintViolation<T>> violations = validator.validate(object);
        if(!violations.isEmpty()) {
            throw new ConstraintViolationException(message, violations);
        }
    }
}
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import lombok.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

@Component
@Slf4j
public class MyCustomWebSocketHandler extends AbstractWebSocketHandler {

    private Validator validator;
    
    @Override
    protected void handleTextMessage(@NonNull WebSocketSession session, @NonNull TextMessage message) {
        CustomMessage customMessage = JSON.parseObject(message.getPayload(), CustomMessage.class);
        // Validate the message according to javax.validation annotations and throw MethodArgumentNotValidException if invalid
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();            
        Set<ConstraintViolation<CustomMessage>> violations = validator.validate(customMessage);
        if(!violations.isEmpty()) {
            throw new ConstraintViolationException(message, violations);
        }

        log.debug("Received valid message {}", customMessage)
    }
}

How to use lambda expression in android?

copy iconCopydownload iconDownload
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
android {
compileSdkVersion 31
buildToolsVersion "30.0.2"

defaultConfig {
    applicationId "in.chikuai.example"
    minSdkVersion 19
    targetSdkVersion 31
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

}
-----------------------
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
android {
compileSdkVersion 31
buildToolsVersion "30.0.2"

defaultConfig {
    applicationId "in.chikuai.example"
    minSdkVersion 19
    targetSdkVersion 31
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

}
-----------------------
plugins {
    id 'com.android.application'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.infiai.simplesender"
        minSdk 25
        targetSdk 31
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    buildFeatures {
        viewBinding true
    }

    compileOptions {
        coreLibraryDesugaringEnabled true
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.9.2'
    implementation group: 'com.alibaba', name: 'fastjson', version: '1.2.78'
    implementation group: 'com.google.guava', name: 'guava', version: '31.0.1-android'
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

how to generate signed apk in android studio

copy iconCopydownload iconDownload
Android Studio Arctic Fox | 2020.3.1 Patch 3
            v1SigningEnabled true
            v2SigningEnabled true
apply plugin: 'com.android.application'

android {
    signingConfigs {
        debug {
            storeFile file('D:\\CodeRepository\\app-key-store\\SimpleSender.jks')
            storePassword 'xxx'
            keyAlias 'simple-sender-key'
            keyPassword 'xxx'
            v1SigningEnabled true
            v2SigningEnabled true
        }
        release {
            storeFile file('D:\\CodeRepository\\app-key-store\\SimpleSender.jks')
            storePassword 'xxx'
            keyAlias 'simple-sender-key'
            keyPassword 'xxx'
            v1SigningEnabled true
            v2SigningEnabled true
        }
    }

.....your other configs.....

}
-----------------------
Android Studio Arctic Fox | 2020.3.1 Patch 3
            v1SigningEnabled true
            v2SigningEnabled true
apply plugin: 'com.android.application'

android {
    signingConfigs {
        debug {
            storeFile file('D:\\CodeRepository\\app-key-store\\SimpleSender.jks')
            storePassword 'xxx'
            keyAlias 'simple-sender-key'
            keyPassword 'xxx'
            v1SigningEnabled true
            v2SigningEnabled true
        }
        release {
            storeFile file('D:\\CodeRepository\\app-key-store\\SimpleSender.jks')
            storePassword 'xxx'
            keyAlias 'simple-sender-key'
            keyPassword 'xxx'
            v1SigningEnabled true
            v2SigningEnabled true
        }
    }

.....your other configs.....

}
-----------------------
Android Studio Arctic Fox | 2020.3.1 Patch 3
            v1SigningEnabled true
            v2SigningEnabled true
apply plugin: 'com.android.application'

android {
    signingConfigs {
        debug {
            storeFile file('D:\\CodeRepository\\app-key-store\\SimpleSender.jks')
            storePassword 'xxx'
            keyAlias 'simple-sender-key'
            keyPassword 'xxx'
            v1SigningEnabled true
            v2SigningEnabled true
        }
        release {
            storeFile file('D:\\CodeRepository\\app-key-store\\SimpleSender.jks')
            storePassword 'xxx'
            keyAlias 'simple-sender-key'
            keyPassword 'xxx'
            v1SigningEnabled true
            v2SigningEnabled true
        }
    }

.....your other configs.....

}

How to don't serialize the class field in FastJson?

copy iconCopydownload iconDownload
@JSONField(serialze=false)
public String getPassword() {
  return password;
}

@JSONField it did not work in spring boot

copy iconCopydownload iconDownload
@Data
@DynamoDBTable(tableName = "xxxx")
public class PointPojo {
    @DynamoDBAttribute(attributeName = "latest_area_point_list")
    private List<Point> latestAreaPointList;

    @Data
    @DynamoDBDocument
    public static class Point {
        @DynamoDBAttribute(attributeName = "point_x")
        private Float pointX;
        @DynamoDBAttribute(attributeName = "point_y")
        private Float pointY;
    }
}

Can't understand/find error in JSON config file referenced by Unity logs

copy iconCopydownload iconDownload
Parse error on line 368:
..., "Weight": 1 }    },    {      "Obje
----------------------^
Expecting ',', ']', got '}'
    {
      "Object": "Leech",
      "Drops": [ [0, 0], [1, 65], [2, 25], [3, 10] ],
      "Loot": [
        { "Item": "Tier2EnchantMats", "Weight": 1 }   <--- line 368 without the comments
    },
    {
      "Object": "Leech",
      "Drops": [ [0, 0], [1, 65], [2, 25], [3, 10] ],
      "Loot": [
        { "Item": "Tier2EnchantMats", "Weight": 1 }
      ]
    },
-----------------------
Parse error on line 368:
..., "Weight": 1 }    },    {      "Obje
----------------------^
Expecting ',', ']', got '}'
    {
      "Object": "Leech",
      "Drops": [ [0, 0], [1, 65], [2, 25], [3, 10] ],
      "Loot": [
        { "Item": "Tier2EnchantMats", "Weight": 1 }   <--- line 368 without the comments
    },
    {
      "Object": "Leech",
      "Drops": [ [0, 0], [1, 65], [2, 25], [3, 10] ],
      "Loot": [
        { "Item": "Tier2EnchantMats", "Weight": 1 }
      ]
    },
-----------------------
Parse error on line 368:
..., "Weight": 1 }    },    {      "Obje
----------------------^
Expecting ',', ']', got '}'
    {
      "Object": "Leech",
      "Drops": [ [0, 0], [1, 65], [2, 25], [3, 10] ],
      "Loot": [
        { "Item": "Tier2EnchantMats", "Weight": 1 }   <--- line 368 without the comments
    },
    {
      "Object": "Leech",
      "Drops": [ [0, 0], [1, 65], [2, 25], [3, 10] ],
      "Loot": [
        { "Item": "Tier2EnchantMats", "Weight": 1 }
      ]
    },

Rails - How to add pagination to Fastjson api?

copy iconCopydownload iconDownload
{
 "data": [
    {
      "id": "1",
      "type": "flashcard",
      "attributes": {
        "question": "why?",
        "answer": "pretty good",
        "slug": null
      }
    },
    {
      "id": "2",
      "type": "flashcard",
      "attributes": {
        "question": "What is 0",
        "answer": "it is 0",
        "slug": null
       }
    },
  ]
  "meta": {
    "page": { "current": 1, "total": 100 }
  },
  "links": {
    "prev": "/example-data?page[before]=yyy&page[size]=1",
    "next": "/example-data?page[after]=yyy&page[size]=1"
  },
}
class FlashcardsController < ApplicationController
  def index
    render json: FlashcardSerializer.new(
      flashcards, { links: {}, meta: { page: { current: 1 } }
    ).serialized_json
  end
end
-----------------------
{
 "data": [
    {
      "id": "1",
      "type": "flashcard",
      "attributes": {
        "question": "why?",
        "answer": "pretty good",
        "slug": null
      }
    },
    {
      "id": "2",
      "type": "flashcard",
      "attributes": {
        "question": "What is 0",
        "answer": "it is 0",
        "slug": null
       }
    },
  ]
  "meta": {
    "page": { "current": 1, "total": 100 }
  },
  "links": {
    "prev": "/example-data?page[before]=yyy&page[size]=1",
    "next": "/example-data?page[after]=yyy&page[size]=1"
  },
}
class FlashcardsController < ApplicationController
  def index
    render json: FlashcardSerializer.new(
      flashcards, { links: {}, meta: { page: { current: 1 } }
    ).serialized_json
  end
end

Error creating bean with name 'projectController': Unsatisfied dependency expressed through field 'service';

copy iconCopydownload iconDownload
 @Mapper
 public interface ProjectMapper extends BaseMapper<Project> {

 }
@SpringBootApplication(exclude = {ShiroAnnotationProcessorAutoConfiguration.class, 
ShiroAutoConfiguration.class, ShiroBeanAutoConfiguration.class})
@EnableDiscoveryClient
@EnableFeignClients
@MapperScan(basePackage="cn.my.pm.project.mapper.*")
public class ProjectApplication {

public static void main(String[] args) {
    SpringApplication.run(ProjectApplication.class, args);
}
-----------------------
 @Mapper
 public interface ProjectMapper extends BaseMapper<Project> {

 }
@SpringBootApplication(exclude = {ShiroAnnotationProcessorAutoConfiguration.class, 
ShiroAutoConfiguration.class, ShiroBeanAutoConfiguration.class})
@EnableDiscoveryClient
@EnableFeignClients
@MapperScan(basePackage="cn.my.pm.project.mapper.*")
public class ProjectApplication {

public static void main(String[] args) {
    SpringApplication.run(ProjectApplication.class, args);
}
-----------------------
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan(value={"org.abc.modules.**.mapper*", "cn.my.pm.**.mapper*"})
public class MybatisPlusConfig {
……
}

APM Go Agent isn't Sending Data to the APM Server

copy iconCopydownload iconDownload
package main

import (
        "fmt"
        "net/http"

        echo "github.com/labstack/echo/v4"

        "go.elastic.co/apm/module/apmechov4"
)

func main() {
        e := echo.New()
        e.Use(apmechov4.Middleware())
        e.GET("/hello/:name", func(c echo.Context) error {
                fmt.Println(c.Param("name"))
                return nil
        })
        http.ListenAndServe(":8080", e)
}
$ ELASTIC_APM_LOG_FILE=stderr ELASTIC_APM_LOG_LEVEL=debug go run main.go
{"level":"debug","time":"2020-08-19T13:33:28+08:00","message":"sent request with 3 transactions, 0 spans, 0 errors, 0 metricsets"}
{"level":"debug","time":"2020-08-19T13:33:46+08:00","message":"gathering metrics"}
{"level":"debug","time":"2020-08-19T13:33:56+08:00","message":"sent request with 0 transactions, 0 spans, 0 errors, 3 metricsets"}
{"level":"error","time":"2020-08-19T13:38:01+08:00","message":"config request failed: sending config request failed: Get \"http://localhost:8200/config/v1/agents?service.name=main\": dial tcp 127.0.0.1:8200: connect: connection refused"}
-----------------------
package main

import (
        "fmt"
        "net/http"

        echo "github.com/labstack/echo/v4"

        "go.elastic.co/apm/module/apmechov4"
)

func main() {
        e := echo.New()
        e.Use(apmechov4.Middleware())
        e.GET("/hello/:name", func(c echo.Context) error {
                fmt.Println(c.Param("name"))
                return nil
        })
        http.ListenAndServe(":8080", e)
}
$ ELASTIC_APM_LOG_FILE=stderr ELASTIC_APM_LOG_LEVEL=debug go run main.go
{"level":"debug","time":"2020-08-19T13:33:28+08:00","message":"sent request with 3 transactions, 0 spans, 0 errors, 0 metricsets"}
{"level":"debug","time":"2020-08-19T13:33:46+08:00","message":"gathering metrics"}
{"level":"debug","time":"2020-08-19T13:33:56+08:00","message":"sent request with 0 transactions, 0 spans, 0 errors, 3 metricsets"}
{"level":"error","time":"2020-08-19T13:38:01+08:00","message":"config request failed: sending config request failed: Get \"http://localhost:8200/config/v1/agents?service.name=main\": dial tcp 127.0.0.1:8200: connect: connection refused"}
-----------------------
package main

import (
        "fmt"
        "net/http"

        echo "github.com/labstack/echo/v4"

        "go.elastic.co/apm/module/apmechov4"
)

func main() {
        e := echo.New()
        e.Use(apmechov4.Middleware())
        e.GET("/hello/:name", func(c echo.Context) error {
                fmt.Println(c.Param("name"))
                return nil
        })
        http.ListenAndServe(":8080", e)
}
$ ELASTIC_APM_LOG_FILE=stderr ELASTIC_APM_LOG_LEVEL=debug go run main.go
{"level":"debug","time":"2020-08-19T13:33:28+08:00","message":"sent request with 3 transactions, 0 spans, 0 errors, 0 metricsets"}
{"level":"debug","time":"2020-08-19T13:33:46+08:00","message":"gathering metrics"}
{"level":"debug","time":"2020-08-19T13:33:56+08:00","message":"sent request with 0 transactions, 0 spans, 0 errors, 3 metricsets"}
{"level":"error","time":"2020-08-19T13:38:01+08:00","message":"config request failed: sending config request failed: Get \"http://localhost:8200/config/v1/agents?service.name=main\": dial tcp 127.0.0.1:8200: connect: connection refused"}

Getting NoSuchMethodError (DestinationAccessor) when launching Spring Boot project with generated Java VDM

copy iconCopydownload iconDownload
com.sap.cloud.s4hana.datamodel:odata-api:jar:2.9.1:compile
com.sap.cloud.sdk.datamodel:odata-core:3.23.0:compile
-----------------------
com.sap.cloud.s4hana.datamodel:odata-api:jar:2.9.1:compile
com.sap.cloud.sdk.datamodel:odata-core:3.23.0:compile

Community Discussions

Trending Discussions on fastjson
  • SpringBoot: Validation without @Valid annotation
  • How to use lambda expression in android?
  • how to generate signed apk in android studio
  • How to don't serialize the class field in FastJson?
  • @JSONField it did not work in spring boot
  • Error when starting spring-boot app. How to find out which dependency is causing AbstractMethodError
  • Can't understand/find error in JSON config file referenced by Unity logs
  • Rails - How to add pagination to Fastjson api?
  • java.lang.StackOverflowError happens when connect to Neo4j, in Springboot Mybatis
  • Error creating bean with name 'projectController': Unsatisfied dependency expressed through field 'service';
Trending Discussions on fastjson

QUESTION

SpringBoot: Validation without @Valid annotation

Asked 2021-Nov-23 at 04:53

I have a web socket handler inherited from AbstractWebSocketHandler that handles text messages. My DTOs use javax.validation.constraints for validation. So, in my REST endpoints, I simply can use the @Valid annotation to invoke the validator. However, as far as I know, this annotation is not usable in my web socket handler. How can I invoke the SpringBoot validator programmatically without this annotation?

Besides, is it possible to use the SpringBoot de-serializer for messages instead of JSON.parseObject?

Example:

import javax.validation.constraints.NotBlank;
import lombok.Data;

@Data
class CustomMessage {
    @NotBlank
    private String text;
}
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import lombok.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

@Component
@Slf4j
public class MyCustomWebSocketHandler extends AbstractWebSocketHandler {
    @Override
    protected void handleTextMessage(@NonNull WebSocketSession session, @NonNull TextMessage message) {
        CustomMessage customMessage = JSON.parseObject(message.getPayload(), CustomMessage.class);
        // Validate the message according to javax.validation annotations and throw MethodArgumentNotValidException if invalid
        log.debug("Received valid message {}", customMessage)
    }
}

ANSWER

Answered 2021-Nov-23 at 04:53

You will use a Validator to fill a list of ConstraintViolation. An example could looks like this :

public abstract class GenericService<T> {

    protected Validator validator;

    protected void validateDomainRecord(T object, String message) {
        Set<ConstraintViolation<T>> violations = validator.validate(object);
        if(!violations.isEmpty()) {
            throw new ConstraintViolationException(message, violations);
        }
    }
}

In your case, your code will looks something like this :

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import lombok.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

@Component
@Slf4j
public class MyCustomWebSocketHandler extends AbstractWebSocketHandler {

    private Validator validator;
    
    @Override
    protected void handleTextMessage(@NonNull WebSocketSession session, @NonNull TextMessage message) {
        CustomMessage customMessage = JSON.parseObject(message.getPayload(), CustomMessage.class);
        // Validate the message according to javax.validation annotations and throw MethodArgumentNotValidException if invalid
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();            
        Set<ConstraintViolation<CustomMessage>> violations = validator.validate(customMessage);
        if(!violations.isEmpty()) {
            throw new ConstraintViolationException(message, violations);
        }

        log.debug("Received valid message {}", customMessage)
    }
}

Take look a this good tutorial for more details. I guess it is also possible to customize your validation and your exception too.

Source https://stackoverflow.com/questions/70029336

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install fastjson

You can download it from GitHub, Maven.
You can use fastjson like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the fastjson component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Consider Popular JSON Processing Libraries
Compare JSON Processing Libraries with Highest Support
Compare JSON Processing Libraries with Permissive License
Compare JSON Processing Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.