简体   繁体   English

无法反序列化 `java.util.LinkedHashMap 类型的值<java.lang.string,java.lang.string> ` 来自 Array 或什么是我的字段的正确类型</java.lang.string,java.lang.string>

[英]Cannot deserialize value of type `java.util.LinkedHashMap<java.lang.String,java.lang.String>` from Array or what would be a correct type of my field

I try to pass a json object to an api on a Spring boot.我尝试在 Spring 启动时将 json object 传递给 api。 Before I was passing values using postman all worked fine.在我使用 postman 传递值之前一切正常。 The format was as follows:格式如下:

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

Now in my Angular app I am passing json as follows:现在在我的 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"}]}

I know the value changed a bit.我知道价值有所改变。 But now I am stuck with how to redeclare the type of a field social links it is where error is pointing to.但是现在我被困在如何重新声明错误指向的字段社交链接的类型上。 Here is how it declared in a model class right now:这是它现在在 model class 中声明的方式:

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

    private  Map<String, String> sociallinks;

And also a converter class:还有一个转换器 class:

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);
            }
          
    }

}

Yet the question is how to redeclare a sociallinks field to send the second request correctly.然而,问题是如何重新声明 sociallinks 字段以正确发送第二个请求。

Update更新

I rediclared the field as list我将该字段重新声明为列表

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

    private  List<String> sociallinks;

But getting the following output in a terminal但是在终端中获取以下 output

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

Update 2 Posting the hall entety class if it is helpful更新 2如果有帮助,请发布大厅实体 class

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;
    }
    
    
    
    
    
    
}

Update 3 And here is my controller function:更新 3这是我的 controller function:

@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);
      }
    }
 

You can use used Map.Entry您可以使用二手Map.Entry

List<Map.Entry<String,String>> sociallinks

after

Map<String,String> sociallinksMap = sociallinks.stream().collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));

暂无
暂无

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

相关问题 class java.util.LinkedHashMap cannot be cast to class java.lang.String (java.util.LinkedHashMap and java.lang.String - class java.util.LinkedHashMap cannot be cast to class java.lang.String (java.util.LinkedHashMap and java.lang.String 找不到能够从类型 [java.util.LinkedHashMap 进行转换的转换器<?, ?> ] 输入 [java.lang.String] - Spring 配置服务器 - No converter found capable of converting from type [java.util.LinkedHashMap<?, ?>] to type [java.lang.String] - Spring config server 如何修复 class java.util.LinkedHashMap 无法转换为 class Z93F725A07428BString.3321C886F46D4 错误。 - how to fix class java.util.LinkedHashMap cannot be cast to class java.lang.String error Spring yaml 属性 java.util.LinkedHashMap 无法转换为 java.lang.String - Spring yaml property java.util.LinkedHashMap cannot be cast to java.lang.String 无法从 mockmvc 的数组值中反序列化 `java.lang.String` 类型的值 - Cannot deserialize value of type `java.lang.String` from Array value from mockmvc 预期的数组类型; 找到:'java.util.map<java.lang.string,java.lang.string> '</java.lang.string,java.lang.string> - Array type expected; found: 'java.util.map<java.lang.String,java.lang.String>' java.lang.String 类型的值数组无法转换为 JSONObject - Value Array of type java.lang.String cannot be converted to JSONObject 面对 JSON 解析问题,无法从数组值 jackson.databind.exc.MismatchedInputException 反序列化类型为“java.lang.String”的值 - Facing JSON parse issue, Cannot deserialize value of type `java.lang.String` from Array value jackson.databind.exc.MismatchedInputException 无法将“java.lang.String”类型的值转换为所需类型 - Cannot convert value of type 'java.lang.String' to required type java.lang.string类型的Java值无法转换为jsonobject - Java value of type java.lang.string cannot be converted to jsonobject
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM