代码之家  ›  专栏  ›  技术社区  ›  Vishal G. Gohel

改装2.0:如何为动态对象生成pojo类

  •  1
  • Vishal G. Gohel  · 技术社区  · 7 年前

    enter image description here 如何为上述类型的响应生成pojo类。

    我已经试过了 http://www.jsonschema2pojo.org/ 和RoboPOJOGenerator

    如果您想尝试,我的JSON字符串是blow。

    {
    "availableDates": {
        "2017-12-31": {
            "from": "08:00",
            "to": "17:00"
        },
        "2017-12-21": {
            "except": [
                {
                    "from": "14:00:00",
                    "to": "14:10:00"
                },
                {
                    "from": "14:11:00",
                    "to": "14:21:00"
                }
            ]
        }
    }
    

    }

    3 回复  |  直到 7 年前
        1
  •  5
  •   Vidhi Dave    7 年前

    1) 转到 http://www.jsonschema2pojo.org/

    2) 将您的响应粘贴到那里,然后输入包和类名

    3) 选择目标语言为Java

    4) 源类型为Json

    5) 注释样式为Gson

    6) 单击预览

    7) 将这些类复制并粘贴到应用程序包中

        2
  •  3
  •   Pankaj Kumar    7 年前

    您不能动态地这样做。尽管您可以使用HashMap解析此类JSON。

    如果您有兴趣这样做,请对页面部分使用以下语法

    private HasMap<String, Page> pages;
    

    它将把页面的JSON解析到上面的HashMap中。您将有“1”、“2”等作为键,页面作为值。


    根据您当前的JSON,解决方案是

    public class AvalDate {
      private HashMap<String, AvailableTimeSlot> availableDates;
    }
    
    public class AvailableTimeSlot {
      private String from;
      private String to;
      private ArrayList<ExceptTimeSlots> except;
    }
    
    public class ExceptTimeSlots {
      private String from;
      private String to;
    }
    

    现在,您可以将解析后的值读取为

    HashMap<String, AvailableTimeSlot> slots = avalDate.geAavailableDates();
    Set keys = slots.keySet();
    for (String date : keys) {
      // Here date is 2017-12-31
      AvailableTimeSlot avt = slots.get(date);
    
      // You can check if except available or not
      if (avt.getExcept() != null) {
        // Read array list of except for that day
        ArrayList<ExceptTimeSlots> except = avt.getExceps();
        // Do whatever you want to do with array
      } else {
        // you can read from and to directlly
        avt.getFrom();
        avt.getTo();
      }
    }
    
        3
  •  0
  •   user9126652 user9126652    7 年前

    伙计们急于否决新秀们的投票,所以用户们,我理解这只是一个澄清,但我不能对此发表评论,所以在这里我祝福你们的否决票。

    操作 ,在中选择这些选项 this site : 1) 目标语言 Java语言 ,
    2) 源类型 JSON ,
    3) 注释样式 Gson公司

    然后尝试生成POJO类。