简体   繁体   English

将 RequestBody json 转换为对象 - Spring Boot

[英]Converting a RequestBody json to an Object - Spring Boot

I am a begineer in java development but has previous experience on programming languages like PHP and Python.我是 Java 开发的初学者,但以前有过 PHP 和 Python 等编程语言的经验。 So little confused on how to proceed on spring boot with the development.对如何在 Spring Boot 上进行开发很少感到困惑。

I am developing a rest API which has the following request我正在开发一个具有以下请求的休息 API

{
  "key":"value",
  "key1":"value1",
  "platform_settings":[
      {"key":"value"}
  ]
}

What I did我做了什么

I created a RestController which accepts the http request and created a function for the resource我创建了一个接受 http 请求的 RestController 并为资源创建了一个函数

public Share share(@RequestBody final Share share) { 
        LOGGER.debug("This is the request", share);
        return share; //
}

Question 1 : If it was any other programming language like PHP or Python, there will be helper function which will accept the json request and convert it to object which I can easily work on.问题 1:如果是 PHP 或 Python 等任何其他编程语言,会有帮助函数接受 json 请求并将其转换为我可以轻松处理的对象。

In python it is as simple as在python中它就像

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)
//can work on json_data anyway I want.

But in java, I will have to create a POJO class, or have jackson/JPA entity as dependency which will map the request to a Class (Which I should predefine with the requests).但是在 java 中,我将不得不创建一个 POJO 类,或者将 jackson/JPA 实体作为依赖项,它将请求映射到一个类(我应该预先定义请求)。

Is there any better way I can do this?有没有更好的方法可以做到这一点? For every request I make, I will have to create a Class which the request can be mapped to and I will have to define the class对于我提出的每个请求,我必须创建一个可以将请求映射到的类,并且必须定义该类

Entity

package com.payunow.socialsharemodule.models;

import java.util.Map;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;


import javax.persistence.Id;


@Entity
public class Share {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String key;
    private String key1;
    private Map<String,String> platform_settings;

    public Share(String name, String description,Map<String,String> platform_settings) {
        this.key = key;
        this.key1 = key1;
        this.platform_settings = platform_settings;
    }

    //for JPA
    public Share() {}

    public String getKey() {
        return key;
    }

    public String getKey1() {
        return key1;
    }

    public Map<String,String> getPlatform_settings() {
        return platform_settings;
    }

}

For every request I make, I will have to create a class defining all its variables inside.对于我提出的每个请求,我都必须创建一个类来定义其内部的所有变量。 Is this the only way to do this?这是唯一的方法吗?

You need to have Jackson dependecy for coversion of json to java object.您需要有 Jackson 依赖才能将 json 转换为 java 对象。 But spring provides it by default, so you don't have to add it explicitly.但是 spring 默认提供了它,所以你不必显式添加它。

You don't need a JPA Entity.您不需要 JPA 实体。 This is needed only when you want to store the recieved data into database.仅当您要将接收到的数据存储到数据库中时才需要这样做。
Just to recieve the request you don't have to create a separate pojo class.只是为了接收请求,您不必创建单独的 pojo 类。 Look at this code看看这个代码

@PostMapping("/json")
public JSONObject getGeneric(@RequestBody String stringToParse){
        JSONParser parser = new JSONParser();
        JSONObject json = null;
        try {
            json = (JSONObject) parser.parse(stringToParse);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    return json;
}   

As you can see here it takes a string as a request and converts it into a generic JSONObject.正如您在此处看到的,它将字符串作为请求并将其转换为通用 JSONObject。 So basically you can pass any json to this endpoint.所以基本上你可以将任何 json 传递给这个端点。

你可以使用 ObjectMapper 类,它有像 convertValue 和 realValue 这样的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 @RequestBody 未将 JSON 映射到 Java 对象 - Spring Boot - @RequestBody not mapping JSON to Java Object - Spring Boot @Requestbody没有得到我的JSON对象Spring-Boot - @Requestbody is not Getting my JSON object Spring-Boot JSON对象在Spring 4.16上为@RequestBody - JSON Object as @RequestBody on Spring 4.16 如何在 spring 引导中将 JSON hasmasp 绑定到 @RequestBody - How to bind JSON hasmasp to the @RequestBody in spring boot 带有可能需要的对象字段的 Spring 启动 RequestBody - Spring boot RequestBody with object fields that could be needed 在 Z38008DD81C2F4D7985ECF6E0CE 中将 Java Object 转换为 JSON 时出现问题 - Problem in converting Java Object to JSON in Spring Boot Spring-Boot JPA-使用JSON RequestBody中的外键插入数据库会导致空对象 - Spring-Boot JPA - Inserting into DB with foreign keys in JSON RequestBody results in null object 如何控制Spring RequestBody将JSON请求主体转换为对象? - How can I control Spring RequestBody converting JSON request body to object? 如何在 Spring Boot 中读取未映射到 @RequestBody 模型对象的其他 JSON 属性 - How to read additional JSON attribute(s) which is not mapped to a @RequestBody model object in Spring boot Spring Boot、Spring MVC JSON RequestBody:未知属性被忽略 - Spring Boot, Spring MVC JSON RequestBody: Unknown property ignored
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM