Parsing JSON to POJO using GSON

后端 未结 2 454
有刺的猬
有刺的猬 2020-12-21 15:22

My JSON looks like follow :

\"message_defaults\": {
      \"LabResultsRequestDefaultMessage\": {
        \"MsgTypeId\": 8,
        \"StaffId\":          


        
相关标签:
2条回答
  • 2020-12-21 15:40

    You can do the following without changing your json structure.

    Type mapType = new TypeToken<Map<String, MessageDefault>>() {}.getType();
    Map<String, MessageDefault> messagesMap = gson.fromJson(json, mapType);
    List<MessageDefault> messages = new ArrayList<MessageDefault>(messagesMap.values());
    
    0 讨论(0)
  • 2020-12-21 15:55

    If you want to get List from json first you have to correct your json. List must be in '[ ]'.

    "message_defaults": [{
          "LabResultsRequestDefaultMessage": {
            "MsgTypeId": 8,
            "StaffId": 122,
            "StaffName": "Willis,Sam",
            "FirstName": "Sam",
            "MI": "D",
            "LastName": "Willis",
            "DefaultMessage": "Lab Department"
          },
          "ReferralRequestDefaultMessage": {
            "MsgTypeId": 6,
            "StaffId": 122,
            "StaffName": "Willis,Sam",
            "FirstName": "Sam",
            "MI": "D",
            "LastName": "Willis",
            "DefaultMessage": "Physican"
          },
          "MessageComposeDefaultMessage": {
            "MsgTypeId": 1,
            "StaffId": 122,
            "StaffName": "Willis,Sam",
            "FirstName": "Sam",
            "MI": "D",
            "LastName": "Willis",
            "DefaultMessage": "Office Manager/Willis Sam"
          }
    }]
    

    EDIT : try this for converting to list

    Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
    Collection<Integer> ints2 = gson.fromJson(json, collectionType);
    

    Follow this link

    0 讨论(0)
提交回复
热议问题