Не может иметь допустимый массив JSON в качестве тела запроса в Spring MVC - PullRequest
0 голосов
/ 13 ноября 2018

Рассмотрим следующую полезную нагрузку JSON, которая действительна с помощью https://jsonformatter.curiousconcept.com/

[  
   {  
      "uid":"6558204851",
      "slot":2,
      "name":"Denis MacIntyre",
      "role":"coopr_role_dmr",
      "state":"coopr_state_ok",
      "position":"[12292.1,8900.03,0.00141907]",
      "timestampWIA":12306.9,
      "loadout":"[['BWA3_MG3','','','',['BWA3_120Rnd_762x51_soft',120],[],'BWA3_bipod_MG3'],[],['BWA3_P8','','','',['BWA3_15Rnd_9x19_P8',15],[],''],['BWA3_Uniform2_sleeves_Fleck',[['ACE_key_west',1],['ACRE_SEM52SL_ID_1',1],['BWA3_DM51A1',1,1],['BWA3_15Rnd_9x19_P8',4,15]]],['BWA3_Vest_Grenadier_Fleck',[['ACE_fieldDressing',1],['ACE_elasticBandage',8],['ACE_quikclot',1],['ACE_EarPlugs',1],['ACE_epinephrine',1],['ACE_morphine',2],['ACE_personalAidKit',1],['BWA3_DM51A1',2,1],['1Rnd_Smoke_Grenade_shell',3,1],['BWA3_120Rnd_762x51_soft',1,120],['BWA3_120Rnd_762x51_Tracer_soft',1,120]]],['BWA3_PatrolPack_Fleck',[['ACE_MapTools',1],['ACE_tourniquet',2],['ACE_Flashlight_MX991',1],['ACE_morphine',2],['ACE_SpraypaintBlue',1],['BWA3_DM32_Red',1,1],['BWA3_DM32_Green',1,1],['BWA3_DM25',5,1],['BWA3_DM32_Orange',1,1],['Chemlight_blue',2,1],['Chemlight_green',2,1],['BWA3_DM51A1',1,1],['BWA3_120Rnd_762x51_Tracer_soft',6,120]]],'BWA3_M92_Fleck','BWA3_G_Combat_clear',['Binocular','','','',[],[],''],['ItemMap','BWA3_ItemNaviPad','ItemRadioAcreFlagged','ItemCompass','ItemWatch','CUP_NVG_HMNVS']]",
      "reputation":10,
      "legacy":3
   },
   {  
      "uid":"6845626561",
      "slot":1,
      "name":"Antoinette Klimuk",
      "role":"coopr_role_engineer",
      "state":"coopr_state_ok",
      "position":"[12292.1,8900.03,0.00141907]",
      "timestampWIA":12306.9,
      "loadout":"[['BWA3_G36A1','','BWA3_acc_LLM01_irlaser','',['BWA3_30Rnd_556x45_G36',30],[],''],[],['BWA3_P8','','','',['BWA3_15Rnd_9x19_P8',15],[],''],['BWA3_Uniform2_sleeves_Fleck',[['ACE_key_west',1],['ACRE_SEM52SL_ID_1',1],['BWA3_DM51A1',1,1],['BWA3_15Rnd_9x19_P8',1,15],['BWA3_DM25',1,1],['BWA3_30Rnd_556x45_G36',1,30]]],['BWA3_Vest_Grenadier_Fleck',[['ACE_fieldDressing',1],['ACE_elasticBandage',8],['ACE_quikclot',1],['ACE_EarPlugs',1],['ACE_epinephrine',1],['ACE_morphine',2],['ACE_DefusalKit',1],['ACE_EntrenchingTool',1],['BWA3_DM51A1',2,1],['1Rnd_Smoke_Grenade_shell',3,1],['BWA3_30Rnd_556x45_G36',7,30],['DemoCharge_Remote_Mag',1,1],['APERSMine_Range_Mag',1,1]]],['BWA3_PatrolPack_Fleck',[['ACE_MapTools',1],['ACE_tourniquet',2],['ACE_Flashlight_MX991',1],['ACE_morphine',2],['ACE_SpraypaintBlue',1],['ACE_wirecutter',1],['ACE_Clacker',1],['ToolKit',1],['BWA3_DM32_Red',1,1],['BWA3_DM32_Green',1,1],['BWA3_DM25',5,1],['BWA3_DM32_Orange',1,1],['Chemlight_blue',2,1],['Chemlight_green',2,1],['BWA3_DM51A1',1,1],['DemoCharge_Remote_Mag',1,1],['BWA3_DM31AT_Mag',1,1],['APERSMine_Range_Mag',2,1],['APERSTripMine_Wire_Mag',1,1],['BWA3_30Rnd_556x45_G36',1,30]]],'BWA3_M92_Fleck','BWA3_G_Combat_clear',['Binocular','','','',[],[],''],['ItemMap','BWA3_ItemNaviPad','ItemRadioAcreFlagged','ItemCompass','ItemWatch','CUP_NVG_HMNVS']]",
      "reputation":25,
      "legacy":6
   }
]

При ее использовании со следующей конечной точкой POST

  @PostMapping(value = "/save/characters/", consumes = MediaType.APPLICATION_JSON_VALUE)
  public void updateCharacters(@RequestBody Characters characters) {
    mongoTemplate.save(characters);
    log.log(Level.INFO, "{} characters have been saved", characters.getCharacters().size());
  }

Где Characters равно

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Characters {
  private List<Character> characters;
}

и Character

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "my_collection")
public class Character {
  // Meta
  @Id
  private String uid;
  private int slot;
  private String name;
  private String role;
  // State
  private String state;
  private String position;
  private double timestampWIA;
  // Equipment
  private String loadout;
  // Scores
  private int reputation;
  private int legacy;

}

происходит сбой со следующим

POST http://localhost:8080/save/characters/

HTTP/1.1 400 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Tue, 13 Nov 2018 16:38:27 GMT
Connection: close

{
  "timestamp": "2018-11-13T16:38:27.161+0000",
  "status": 400,
  "error": "Bad Request",
  "message": "JSON parse error: Cannot deserialize instance of `com.coopr.hq.models.Characters` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.coopr.hq.models.Characters` out of START_ARRAY token\n at [Source: (PushbackInputStream); line: 1, column: 1]"
  "path": "/save/characters/"
}

Ответы [ 2 ]

0 голосов
/ 13 ноября 2018

Ваш json не в правильном формате, он должен начинаться с символов, как показано ниже: как упомянуто @ luk2302

Ваше отображение классов pojo должно быть таким же, как ваш json, и в json у вас нет переменной символов, но в pojo вы создаете переменную с этим именем, либо удалите эту переменную из pojo, либо добавьте эту переменную в свой json.

{
   characters:
    [  
       {  
          "uid":"6558204851",
          "slot":2,
          "name":"Denis MacIntyre",
          "role":"coopr_role_dmr",
          "state":"coopr_state_ok",
          "position":"[12292.1,8900.03,0.00141907]",
          "timestampWIA":12306.9,
          "loadout":"[['BWA3_MG3','','','',['BWA3_120Rnd_762x51_soft',120],[],'BWA3_bipod_MG3'],[],['BWA3_P8','','','',['BWA3_15Rnd_9x19_P8',15],[],''],['BWA3_Uniform2_sleeves_Fleck',[['ACE_key_west',1],['ACRE_SEM52SL_ID_1',1],['BWA3_DM51A1',1,1],['BWA3_15Rnd_9x19_P8',4,15]]],['BWA3_Vest_Grenadier_Fleck',[['ACE_fieldDressing',1],['ACE_elasticBandage',8],['ACE_quikclot',1],['ACE_EarPlugs',1],['ACE_epinephrine',1],['ACE_morphine',2],['ACE_personalAidKit',1],['BWA3_DM51A1',2,1],['1Rnd_Smoke_Grenade_shell',3,1],['BWA3_120Rnd_762x51_soft',1,120],['BWA3_120Rnd_762x51_Tracer_soft',1,120]]],['BWA3_PatrolPack_Fleck',[['ACE_MapTools',1],['ACE_tourniquet',2],['ACE_Flashlight_MX991',1],['ACE_morphine',2],['ACE_SpraypaintBlue',1],['BWA3_DM32_Red',1,1],['BWA3_DM32_Green',1,1],['BWA3_DM25',5,1],['BWA3_DM32_Orange',1,1],['Chemlight_blue',2,1],['Chemlight_green',2,1],['BWA3_DM51A1',1,1],['BWA3_120Rnd_762x51_Tracer_soft',6,120]]],'BWA3_M92_Fleck','BWA3_G_Combat_clear',['Binocular','','','',[],[],''],['ItemMap','BWA3_ItemNaviPad','ItemRadioAcreFlagged','ItemCompass','ItemWatch','CUP_NVG_HMNVS']]",
          "reputation":10,
          "legacy":3
       },
       {  
          "uid":"6845626561",
          "slot":1,
          "name":"Antoinette Klimuk",
          "role":"coopr_role_engineer",
          "state":"coopr_state_ok",
          "position":"[12292.1,8900.03,0.00141907]",
          "timestampWIA":12306.9,
          "loadout":"[['BWA3_G36A1','','BWA3_acc_LLM01_irlaser','',['BWA3_30Rnd_556x45_G36',30],[],''],[],['BWA3_P8','','','',['BWA3_15Rnd_9x19_P8',15],[],''],['BWA3_Uniform2_sleeves_Fleck',[['ACE_key_west',1],['ACRE_SEM52SL_ID_1',1],['BWA3_DM51A1',1,1],['BWA3_15Rnd_9x19_P8',1,15],['BWA3_DM25',1,1],['BWA3_30Rnd_556x45_G36',1,30]]],['BWA3_Vest_Grenadier_Fleck',[['ACE_fieldDressing',1],['ACE_elasticBandage',8],['ACE_quikclot',1],['ACE_EarPlugs',1],['ACE_epinephrine',1],['ACE_morphine',2],['ACE_DefusalKit',1],['ACE_EntrenchingTool',1],['BWA3_DM51A1',2,1],['1Rnd_Smoke_Grenade_shell',3,1],['BWA3_30Rnd_556x45_G36',7,30],['DemoCharge_Remote_Mag',1,1],['APERSMine_Range_Mag',1,1]]],['BWA3_PatrolPack_Fleck',[['ACE_MapTools',1],['ACE_tourniquet',2],['ACE_Flashlight_MX991',1],['ACE_morphine',2],['ACE_SpraypaintBlue',1],['ACE_wirecutter',1],['ACE_Clacker',1],['ToolKit',1],['BWA3_DM32_Red',1,1],['BWA3_DM32_Green',1,1],['BWA3_DM25',5,1],['BWA3_DM32_Orange',1,1],['Chemlight_blue',2,1],['Chemlight_green',2,1],['BWA3_DM51A1',1,1],['DemoCharge_Remote_Mag',1,1],['BWA3_DM31AT_Mag',1,1],['APERSMine_Range_Mag',2,1],['APERSTripMine_Wire_Mag',1,1],['BWA3_30Rnd_556x45_G36',1,30]]],'BWA3_M92_Fleck','BWA3_G_Combat_clear',['Binocular','','','',[],[],''],['ItemMap','BWA3_ItemNaviPad','ItemRadioAcreFlagged','ItemCompass','ItemWatch','CUP_NVG_HMNVS']]",
          "reputation":25,
          "legacy":6
       }
    ]
}

ПРИМЕЧАНИЕ: Вы также должны использовать продукцию в пост-звонке, как показано ниже:

@PostMapping(value = "/save/characters/", produces=MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
  public void updateCharacters(@RequestBody Characters characters) {
    mongoTemplate.save(characters);
    log.log(Level.INFO, "{} characters have been saved", characters.getCharacters().size());
  }

Существует другой подход: не меняйте свой json, просто удалите класс символов и просто сохраните класс символов и измените свой код, как показано ниже:

@PostMapping(value = "/save/characters/", produces=MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
      public void updateCharacters(@RequestBody List<Character> character) {
        mongoTemplate.save(characters);
        log.log(Level.INFO, "{} characters have been saved", characters.getCharacters().size());
      }
0 голосов
/ 13 ноября 2018

JSON не соответствует вашему Characters классу. JSON должен быть:

{
    characters: [ { "uid" : "6558204851", ... }, { ... } ]
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...