0

我尝试在 Spring Boot 上将 json 对象传递给 api。在我使用邮递员传递值之前,一切都很好。格式如下:

{
    "shortname": "test2",
    "fullname": "testing2",
    "address": "addrtest2",
    "telephone": "380979379993",
    "website": "www.site2.com",
    "sociallinks":
    {
        "facebook": "fb2.com"
    },
    "foundationyear": "1992"
}

现在在我的 Angular 应用程序中,我传递 json 如下:

{"shortname":"test","fullname":"Bogdan Onyshenko","address":"Пр. Победы 72в","telephone":"0669829242","website":"http://193.70.37.242/index.php?route=extension/feed/google_sitemap","foundationyear":"2004","sociallinks":[{"network":"facebook","linkpage":"fb.com"}]}

我知道值改变了一点。但是现在我被困在如何重新声明错误所指向的字段社交链接的类型。这是它现在在模型类中声明的方式:

@Column(name = "sociallinks")
      @Convert(converter = StringMapConverter.class)

    private  Map<String, String> sociallinks;

还有一个转换器类:

package com.example.helpers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class StringMapConverter implements AttributeConverter<Map<String, String>, String> {

      private static ObjectMapper mapper;
      static {
            // To avoid instantiating ObjectMapper again and again.
            mapper = new ObjectMapper();
          }

    
    @Override
    public String convertToDatabaseColumn(Map<String, String>  data) {
         if (null == data) { 
              // You may return null if you prefer that style
              return "{}";
            }
            
            try {
              return mapper.writeValueAsString(data);
              
            } catch (IOException e) {
              throw new IllegalArgumentException("Error converting map to JSON", e);
            }
    }

    @Override
    public Map<String, String> convertToEntityAttribute(String s) {
         if (null == s) {
              // You may return null if you prefer that style
              return new HashMap<>();
            }

            try {
              return mapper.readValue(s, new TypeReference<Map<String, String>>() {});
              
            } catch (IOException e) {
              throw new IllegalArgumentException("Error converting JSON to map", e);
            }
          
    }

}

然而问题是如何重新声明一个社交链接字段以正确发送第二个请求。

更新

我将该字段重新声明为列表

@Column(name = "sociallinks")
      //@Convert(converter = StringMapConverter.class)

    private  List<String> sociallinks;

但是在终端中获得以下输出

2022-01-20 08:36:07.040 DEBUG 18908 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : POST "/buildcompanies/add", parameters={}
2022-01-20 08:36:07.040 DEBUG 18908 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.example.controller.BuildingcompaniesController#createCompany(Buildcompanies)
2022-01-20 08:36:07.042 DEBUG 18908 --- [nio-8080-exec-3] o.s.web.method.HandlerMethod             : Could not resolve parameter [0] in public org.springframework.http.ResponseEntity<com.example.model.Buildcompanies> com.example.controller.BuildingcompaniesController.createCompany(com.example.model.Buildcompanies): JSON parse error: Cannot deserialize value of type `java.util.ArrayList<java.lang.Object>` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList<java.lang.Object>` from Object value (token `JsonToken.START_OBJECT`)
 at [Source: (PushbackInputStream); line: 1, column: 230] (through reference chain: com.example.model.Buildcompanies["sociallinks"]->java.util.ArrayList[0])
2022-01-20 08:36:07.042  WARN 18908 --- [nio-8080-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.ArrayList<java.lang.Object>` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList<java.lang.Object>` from Object value (token `JsonToken.START_OBJECT`)<EOL> at [Source: (PushbackInputStream); line: 1, column: 230] (through reference chain: com.example.model.Buildcompanies["sociallinks"]->java.util.ArrayList[0])]
2022-01-20 08:36:07.042 DEBUG 18908 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Completed 400 BAD_REQUEST
2022-01-20 08:36:07.043 DEBUG 18908 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for POST "/error", parameters={}
2022-01-20 08:36:07.043 DEBUG 18908 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2022-01-20 08:36:07.043 DEBUG 18908 --- [nio-8080-exec-3] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'application/json', given [application/json] and supported [application/json, application/*+json, application/json, application/*+json]
2022-01-20 08:36:07.043 DEBUG 18908 --- [nio-8080-exec-3] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Writing [{timestamp=Thu Jan 20 08:36:07 EET 2022, status=400, error=Bad Request, path=/buildcompanies/add}]
2022-01-20 08:36:07.044 DEBUG 18908 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 400

更新 2 如果有帮助,请发布大厅实体课程

package com.example.model;
import java.beans.Transient;
import java.util.List;
import java.util.Map;

import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import com.example.helpers.StringMapConverter;
@Entity
@Table(name = "buildingcompanies")

public class Buildcompanies {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @Column(name = "shortname")
    private String shortname;
    @Column(name = "fullname")
    private String fullname;
    @Column(name = "address")
    private String address;
    @Column(name = "telephone")
    private String telephone;
    @Column(name = "website")
    private String website;
    @Column(name = "sociallinks")
      @Convert(converter = StringMapConverter.class)

    private  List<String> sociallinks;
    @Column(name = "foundationyear")
    private String foundationyear;
    private transient double rating;
    
    public Buildcompanies() {

    }

    public Buildcompanies(String shortname, String fullname, String address, String telephone, String website,
            List<String> map, String foundationyear) {
        this.shortname = shortname;
        this.fullname = fullname;
        this.address = address;
        this.telephone = telephone;
        this.website = website;
        this.sociallinks = map;
        this.foundationyear = foundationyear;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getShortname() {
        return shortname;
    }

    public void setShortname(String shortname) {
        this.shortname = shortname;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }

    

    public List<String> getSociallinks() {
        return sociallinks;
    }

    public void setSociallinks(List<String> sociallinks) {
        this.sociallinks = sociallinks;
    }

    public String getFoundationyear() {
        return foundationyear;
    }

    public void setFoundationyear(String foundationyear) {
        this.foundationyear = foundationyear;
    }

    public double getRating() {
        return rating;
    }

    public void setRating(double rating) {
        this.rating = rating;
    }
    
    
    
    
    
    
}

更新 3 这是我的控制器功能:

@PostMapping("/add")
    public ResponseEntity<Buildcompanies> createCompany(@RequestBody Buildcompanies company) {
      try {
        Buildcompanies _company = buildcompaniesRepository
            .save(new Buildcompanies(company.getFullname(), company.getShortname(), company.getAddress(), company.getTelephone(), company.getWebsite(), company.getSociallinks(), company.getFoundationyear()));
        return new ResponseEntity<>(_company, HttpStatus.CREATED);
      } catch (Exception e) {
       System.out.println(e.getMessage());
          return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
      }
    }
 
4

0 回答 0