2014-05-20 53 views
0

拥有一个对象字段带有4个字段,如String,Integer和Date(timestamp)。然后列出这些对象。List <Objects> to Json文件

需要写一个json格式的文件,该文件映射列表 objects.I将独立更新json文件上的每个对象。

这将是最好的方法来做到这一点?我玩过ObjectMapper,但无法实现这一点。

尝试这样:

ObjectMapper mapper = new ObjectMapper();// this is Jackson 
File file = new File("/parameter.json"); 
Map<String,Integer> parameters = new HashMap<String, Integer>(); 
for(Parameter par : Parameter.values()){ 
parameters.put(par.getName(),par.getValue1()); 
} 
mapper.writeValue(file, parameters); 
+2

让我们来看看一些代码。 – Mena

+0

为此,请使用[Gson](https://code.google.com/p/google-gson/)或[Jackson](http://jackson.codehaus.org/)之类的内容。 –

回答

-1

您可以使用杰克逊。首先你应该创建一个对象来保存所有这些字段。对象应该有getter/setter方法。然后你可以使用ObjectMapper来写入一个文件。

示例代码:

public class NewMain { 

    public static void main(String[] args) { 

     try { 

      ObjectMapper mapper = new ObjectMapper(); 

      mapper.writeValue(new File("/parameter.json"), new YourObject(1, "some string", "another string")); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
    } 
} 

class YourObject { 

    private int a; 
    private String b; 
    private String c; 

    public YourObject(int a, String b, String c) { 
     this.a = a; 
     this.b = b; 
     this.c = c; 
    } 

    public int getA() { 
     return a; 
    } 

    public void setA(int a) { 
     this.a = a; 
    } 

    public String getB() { 
     return b; 
    } 

    public void setB(String b) { 
     this.b = b; 
    } 

    public String getC() { 
     return c; 
    } 

    public void setC(String c) { 
     this.c = c; 
    } 

和输出是

{"a":1,"b":"some string","c":"another string"}