【问题标题】:json (which contains few objects) to TreeMap on javajson(包含很少的对象)到java上的TreeMap
【发布时间】:2017-02-23 22:01:17
【问题描述】:

有人可以显示将 json 反序列化为 TreeMap 的代码吗?一些简单的例子,其中包括 json 的例子 我会展示我尝试过的 首先我是新手所以请原谅我 那是我的 json(可能我在这里也有错误):

{"Car":[{"mark":"AUDI_A3", "colour": "black"},
{"mark":"BMW_m3", "colour": "white"}]}

我的代码不起作用

public static void main(String[] args) {
        open();
    }
    private static void open(){
        try {
            BufferedReader buff = new BufferedReader(new FileReader("C:\Users\\t1.json"));
            String bf=null;
            String json= null;
            while((bf=buff.readLine())!=null){
                json+=bf;
            }
            Gson gson = new Gson();
            Type type = new TypeToken<TreeMap<String, SmallGuys>>(){}.getType();
            TreeMap<String, SmallGuys> Platoon = gson.fromJson(json, type);
            System.out.print(Platoon.keySet());
        }
        catch (Exception e){
            System.out.println("There is a mistake");
        }
    }

【问题讨论】:

  • 你看过Convert Json to Map吗?
  • 刚试过,没有帮助 final Type Map = new TypeToken>() { }.getType(); Gson gson = 新 Gson(); JsonReader 阅读器 = 新 JsonReader(buff); TreeMap data = gson.fromJson(reader, Map); // 包含整个评论列表 System.out.print(data.keySet());
  • 我的 json 呢?也许有错误&
  • Convert Json to Map的可能重复

标签: java json collections deserialization treemap


【解决方案1】:

对于杰克逊,我放了一些方法:

public static Object convertJsonRequestToObject(HttpServletRequest pRequest, Class<?> pObject) throws JsonParseException, JsonMappingException, IOException {
    return new ObjectMapper().readValue(IOUtils.toString(pRequest.getInputStream(), StandardCharsets.UTF_8), pObject);
}

public static Map<String,Object> parseJsonToMap(String json) throws JsonParseException, JsonMappingException, IOException{
    return   new ObjectMapper().readValue(json, HashMap.class);
}

public static Map<String,Object> parseObjectToMap(Object object){
    return  (Map<String, Object>) new ObjectMapper().convertValue(object, Map.class);
}

//inverse
public static Object parseMapToObject(Map<?, ?> pMap, Class<?> pClass){
    return new ObjectMapper().convertValue(pMap, pClass);
}

【讨论】:

  • {"batchSize":10,"batchIndex":1,"inventoryInformation":{"inventoryName":"Test","userName":"jason.gonzalez","beginDate":"2017 -02-16","endDate":"2017-02-23","category":"2"}} 和这个 JSON 的实体 public class InventoryInput { private int batchIndex;私有 int 批处理大小;私有 HashMap 库存信息; public InventoryInput(){ } //设置和获取 }
  • 我也可以在实体上添加要转换的对象,例如: var user = { fullName: getCurrentSpotUser() } var location = { idLocation: spotInformation.locationId, user } var inventory = { idInventory: inventoryGeneralInformation .inventoryData.inventoryId } dataSend.inventoryInformation = { location, inventory };
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
  • 2015-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多