使用ObjectMapper解析字符串json到对象

时间:2014-09-26 08:12:08

标签: java json jackson

我要解析

[{'lng':116.298871, 'lat':39.991466},{'lng':116.298871, 'lat':39.990079},{'lng':116.295787, 'lat':39.990079},{'lng':116.295787, 'lat':39.991466}]]

到区域或坐标对象,但失败了, 我用objectMapper.readValue (str, Coordinate[].class); 并且objectMapper.readValue (str, Region.class);都没有完成。 在地区

public class Region implements Serializable{       
    private static final long serialVersionUID = 1233772272079216259L;    
    private List<Coordinate> boudary;        
    public List<Coordinate> getBoudary() {
        return boudary;
    }   
    public void setBoudary(List<Coordinate> boudary) {
        this.boudary = boudary;
    }
}

package com.compass.goverment.resource.bean.logic;   
    public class Coordinate {           
        private double lng;          
        private double lat;                  
        public Coordinate (double lng, double lat) {     
            super ();
            this.lng = lng;
            this.lat = lat;
        }

        public double getLng () {           
            return lng;
        }       

        public void setLng (double lng) {           
            this.lng = lng;
        }                   
        public double getLat () {          
            return lat;
        }                   
        public void setLat (double lat) {            
            this.lat = lat;
        }                      
    }

如何使用ObjectMapper将字符串json解析为region对象?

1 个答案:

答案 0 :(得分:0)

在Coordinate类中有一个默认构造函数,然后

String json= "[{'lng':116.298871, 'lat':39.991466},{'lng':116.298871, 'lat':39.990079}
    ,{'lng':116.295787, 'lat':39.990079},{'lng':116.295787, 'lat':39.991466}]]";
Gson gson = new Gson();
java.lang.reflect.Type collectionType= new TypeToken<List<Coordinate>>() {}.getType();
List<Coordinate> userList = gson.fromJson(json, collectionType);
System.out.println(userList);