【问题标题】:Convert Java Object to Json and Vice versa?将 Java 对象转换为 Json,反之亦然?
【发布时间】:2013-08-09 00:42:56
【问题描述】:

我知道 JSON 对象不过是 String

我的问题是我有一个对象映射,我想将其转换为 Json 格式。

例子:

Java Class ->
Class Person{
  private String name;
  private String password;
  private int number;
}

Java list ->
Map<List<Long>,List<Person>> map=new HashMap<List<Long>,List<Person>>();
..and map has Some data filled in it.

我想将该列表转换为

 Json Format?

我怎样才能实现它?因为我想通过 HttpClient 发送它...... 如果不是,其他替代方法是什么?

据我所知,有Gson API 可用,但我不知道如何使用它或以其他有效的方式使用它。

谢谢

【问题讨论】:

    标签: java json spring-mvc


    【解决方案1】:

    你也可以使用杰克逊。

        Person person= new Person();
    ObjectMapper mapper = new ObjectMapper();
    
    try {
    
        // convert personobject to json string, and save to a file
        mapper.writeValue(new File("c:\\person.json"), person);
    
        // display to console
        System.out.println(mapper.writeValueAsString(person));
    
    } catch (Exception e) {
    
        e.printStackTrace();
    
    } 
    

    反之亦然

        ObjectMapper mapper = new ObjectMapper();
    
    try {
    
        // read from file, convert it to user class
        Person person= mapper.readValue(new File("c:\\person.json"), Person.class);
    
        // display to console
        System.out.println(person);
    
    } catch (Exception e) {
    
        e.printStackTrace();
    
    }
    

    使用 jackson 将此依赖项添加到您的 POM.xml

    <repositories>
    <repository>
        <id>codehaus</id>
        <url>http://repository.codehaus.org/org/codehaus</url>
    </repository>
    </repositories>
    
    <dependencies>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.8.5</version>
    </dependency>
    </dependencies>
    

    【讨论】:

      【解决方案2】:

      我得到了答案,但感谢您的回复。

       Map<Long,List<Person>> map=new HashMap<Long,List<Person>>();
          //adding some data
      
      Gson gson=new Gson();
      String mapJsonStr=gson.toJson(map);
      
      //mapJsonStr : is my map's JSon Strin
      

      反向

       TypeToken<Map<Long,List<Person>>> token = new TypeToken<Map<Long,List<Person>>>(){};
          Map<Long,List<Person>> map_new=new HashMap<Long,List<Person>>();
          map_new=gson.fromJson(mapJsonStr,token.getType());
      
          //origian map
      // map_new is my Map get from map's Json String
      

      就是这样。谢谢

      【讨论】:

      【解决方案3】:

      使用 Gson 在客户端使用 Gson 转换为 Json。

      发送字符串数组。

          String[] subscriberArray = new String[]{"eee", "bbb"}; 
          Gson gson = new Gson();
          String recipientInfoStringFormat = gson.toJson(subscriberArray);    
      

      发送用户定义类型的数组。

              RecipientInfo[] recipientInfos = new RecipientInfo[1];
      
              RecipientInfo ri = new RecipientInfo();
              ri.setA(1);
              ri.setB("ss");
      
              recipientInfos.add(ri);
      
              Gson gson = new Gson();
              String recipientInfoStringFormat = gson.toJson(recipientInfos);     
      

      在服务器端使用 Gson 读取数据。

      对于原始类型。

                  String subscriberArrayParam = req.getParameter("subscriberArrayParam"); 
          Gson gson = new Gson();
          String[] subscriberArray = gson.fromJson(subscriberArrayParam, String[].class);     
          for (String str : subscriberArray) {
              System.out.println("qq :"+str);
          }
      

      对于用户定义的对象

          String recipientInfos = req.getParameter("recipientInfoStringFormat");
      
          Gson gson = new Gson();
          RecipientInfo[] ri = gson.fromJson(recipientInfos, RecipientInfo[].class);  
      

      【讨论】:

        【解决方案4】:

        不确定 Gson 的问题是什么。来自the doc

        BagOfPrimitives obj = new BagOfPrimitives();
        Gson gson = new Gson();
        String json = gson.toJson(obj); 
        

        BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);  
        

        该对象(顾名思义)由原语组成。然而,Gson 将简单地处理对象、对象集合等。使用泛型等时生活会变得更复杂一些,但是对于上面的示例,我希望 Gson 可以轻松工作。

        【讨论】:

        • 如果有非原始类型怎么办?
        • @HarshadDeshmukh Gson 也会解析它们,除非有自引用并且会导致无限的 json
        猜你喜欢
        • 1970-01-01
        • 2015-03-05
        • 2011-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多