简体   繁体   中英

how to store JSON in POSTGRES using SpringBoot + JPA?

I have a payload that am trying to save into a database, whenever I post the payload, it returns the mapped JSON objects as null instead of the values in the payload passed.

here is the JSON payload

{
    "authStatus": {
        "authStatusCode": 131,
        "authStatusDescription": "API call doesn't need authentication"
    },
    "results": {
        "beepTransactionID": 10764659,
        "payerTransactionID": "5f51eed7347a7",
        "statusCode": "188",
        "statusDescription": "Response was received"
    }
}

after posting it to postman

{
    "id": 14,
    "authStatusCode": null,
    "authStatusDescription": null,
    "beepTransactionID": null,
    "payerTransactionID": null,
    "statusCode": null,
    "statusDescription": null
}

my controller for posting

     @PostMapping("/payload")
        public Payload createPayload(@Valid @RequestBody Payload payload) {
            return payloadRepository.save(payload);
        }

my model

@Entity
@Table(name = "payload", schema = "public")
    public class Payload {
        private long id;
        Integer authStatusCode;
        String authStatusDescription;
        Integer beepTransactionID;
        String payerTransactionID;
        String statusCode;
        String statusDescription;
    
        public Payload(){
    
        }
    
    //getters and setters

You need intermediary objects, Payload needs to be a bit deeper to match exactly the format of your JSON object

public class Payload {
    AuthStatus authStatus;
    Results results;
    // Add boilerplate code here
}

public class AuthStatus {
    Integer authStatusCode;
    String authStatusDescription;
    // Add boilerplate code here
}

public class Results {
    Integer beepTransactionID;
    String payerTransactionID;
    String statusCode;
    String statusDescription;
    // Add boilerplate code here
}

Try using

@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")

to store payload into JsonNode format as it is

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM