2014-04-28 44 views
2

我試圖創建一個Java REST端點,它返回JQuery數據數組以供JQuery FLOT圖表插件使用。Jackson2 Java到Json數組在創建數組時忽略字段名稱

至少,對於FLOT JSON數據需要是數字數組,即

[ [x1, y1], [x2, y2], ... ] 

鑑於我有Point對象的一個​​列表,爪哇即

List<Point> data = new ArrayList<>(); 

其中點被定義作爲

public class Point { 

    private final Integer x; 
    private final Integer y; 

    public Point(Integer x, Integer y) { 
     this.x = x; 
     this.y = y; 
    } 

    ... 
} 

什麼方法或Jackson2註釋,如果有的話,我需要把Java對象得到正確的JSON格式。目前我得到的輸出格式爲:

[{x:x1, y:y1}, {x:x2, y:y2} ...] 

當我需要這樣的格式:

[[x1,y1], [x2,y2] ...] 
+0

你需要什麼是不是一個有效的JSON .. – gipinani

+0

我只是概述格式之間的差異,而不是完整的語法:) –

+0

@mserioli最終的Flot格式是有效的JSON ...數組陣列...訣竅是Ayub需要一個定製的Jackson「Object Mapper/Resolver」來返回x,y作爲數組還是作爲地圖。 (我不知道這個映射器/解析器的傑克遜術語是什麼) – scunliffe

回答

1

您可以編寫自定義Point串行

import java.io.IOException; 

import org.codehaus.jackson.JsonGenerator; 
import org.codehaus.jackson.JsonProcessingException; 
import org.codehaus.jackson.map.JsonSerializer; 
import org.codehaus.jackson.map.SerializerProvider; 

public class CustomPointSerializer extends JsonSerializer<Point> { 

    @Override 
    public void serialize(Point point, JsonGenerator gen, SerializerProvider provider) throws IOException, JsonProcessingException { 
     gen.writeStartArray(); 
     gen.writeNumber(point.getX()); 
     gen.writeNumber(point.getY()); 
     gen.writeEndArray(); 
    } 
} 

那麼你可以自定義序列化器類設置爲您Point

import org.codehaus.jackson.map.annotate.JsonSerialize; 

@JsonSerialize(using = CustomPointSerializer.class) 
public class Point { 

    private Integer x; 
    private Integer y; 

    public Point(Integer x, Integer y) { 
     this.x = x; 
     this.y = y; 
    } 

    public Integer getX() { 
     return x; 
    } 

    public void setX(Integer x) { 
     this.x = x; 
    } 

    public Integer getY() { 
     return y; 
    } 

    public void setY(Integer y) { 
     this.y = y; 
    } 
} 

,並嘗試

ObjectMapper mapper = new ObjectMapper(); 
List<Point> points = new ArrayList<Point>(); 
points.add(new Point(1,2)); 
points.add(new Point(2,3)); 
System.out.println(mapper.writeValueAsString(points)); 

代碼產生以下結果

[[1,2],[2,3]] 

希望這會有所幫助。

+0

我用了這個答案的一個稍微修改過的版本,但是它幫助 –

+0

我很高興我能幫忙,問候。 – vzamanillo

1

您可以使用@JsonView註釋上返回intergers數組的特殊的getter方法。這裏有一個例子:

public class JacksonObjectAsArray { 
    static class Point { 

     private final Integer x; 
     private final Integer y; 

     public Point(Integer x, Integer y) { 
      this.x = x; 
      this.y = y; 
     } 

     @JsonValue 
     public int[] getXY() { 
      return new int[] {x, y}; 
     } 
    } 

    public static void main(String[] args) throws JsonProcessingException { 
     ObjectMapper mapper = new ObjectMapper(); 
     System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Point(12, 45))); 
    } 

} 

輸出:

[ 12, 45 ]