Я пытаюсь передать объект json в API при загрузке Spring. До того, как я передавал значения с помощью почтальона, все работало нормально. Формат был следующий:
{
"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=ex ... ociallinks":[{"network":"facebook","linkpage":"fb.com"}]}
Я знаю, что значение немного изменилось. Но теперь я застрял в том, как переопределить тип поля социальных ссылок, на которое указывает ошибка. Вот как это объявлено в классе модели прямо сейчас:
@Column(name = "sociallinks")
@Convert(converter = StringMapConverter.class)
private Map 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 {
private static ObjectMapper mapper;
static {
// To avoid instantiating ObjectMapper again and again.
mapper = new ObjectMapper();
}
@Override
public String convertToDatabaseColumn(Map 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 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() {});
} catch (IOException e) {
throw new IllegalArgumentException("Error converting JSON to map", e);
}
}
}
Однако вопрос заключается в том, как переопределить поле социальных ссылок, чтобы правильно отправить второй запрос.
Обновить
Я переопределил поле как список
@Column(name = "sociallinks")
//@Convert(converter = StringMapConverter.class)
private List 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.controller.BuildingcompaniesController.createCompany(com.example.model.Buildcompanies): JSON parse error: Cannot deserialize value of type `java.util.ArrayList` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList` 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` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList` 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 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
Публикация класса Entity Hall, если это полезно
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 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 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 getSociallinks() {
return sociallinks;
}
public void setSociallinks(List 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 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);
}
}
Подробнее здесь: https://stackoverflow.com/questions/707 ... tring-java
Невозможно десериализовать значение типа `java.util.LinkedHashMap<java.lang.String,java.lang.String>` из массива или пра ⇐ JAVA
Программисты JAVA общаются здесь
1764050750
Anonymous
Я пытаюсь передать объект json в API при загрузке Spring. До того, как я передавал значения с помощью почтальона, все работало нормально. Формат был следующий:
{
"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 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 {
private static ObjectMapper mapper;
static {
// To avoid instantiating ObjectMapper again and again.
mapper = new ObjectMapper();
}
@Override
public String convertToDatabaseColumn(Map 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 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() {});
} catch (IOException e) {
throw new IllegalArgumentException("Error converting JSON to map", e);
}
}
}
Однако вопрос заключается в том, как переопределить поле социальных ссылок, чтобы правильно отправить второй запрос.
[b]Обновить[/b]
Я переопределил поле как список
@Column(name = "sociallinks")
//@Convert(converter = StringMapConverter.class)
private List 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.controller.BuildingcompaniesController.createCompany(com.example.model.Buildcompanies): JSON parse error: Cannot deserialize value of type `java.util.ArrayList` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList` 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` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.ArrayList` 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 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
[b]Обновление 2[/b]
Публикация класса Entity Hall, если это полезно
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 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 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 getSociallinks() {
return sociallinks;
}
public void setSociallinks(List 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;
}
}
[b]Обновление 3[/b]
А вот моя функция контроллера:
@PostMapping("/add")
public ResponseEntity 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);
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/70781588/cannot-deserialize-value-of-type-java-util-linkedhashmapjava-lang-string-java[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия