将 Java 对象转换为 Json,反之亦然?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18106778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:26:48  来源:igfitidea点击:

Convert Java Object to Json and Vice versa?

javajsonspring-mvc

提问by Oomph Fortuity

I know that JSON object is nothing but the String.

我知道 JSON 对象只不过是String.

My question is that I have a Map of Object and i want to convert it into Json format.

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

Example :

例子 :

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.

I want to convert that list into

我想将该列表转换为

 Json Format?

How I can achieve it? Because i want to send it over HttpClient... If not what is the other alternative way?

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

As per my knowledge there is Gson APIavailable, but I dont know how to use it and or in other efficient way.

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

Thank you

谢谢

采纳答案by Oomph Fortuity

I got my Answer but Thank you for Your Responses.

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

 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

for reverse

反向

 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

That's It.Thank you

就是这样。谢谢

回答by Brian Agnew

Not sure what the problem with Gson is. From the doc:

不确定 Gson 的问题是什么。从文档

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

and

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

That object is (as the name suggests) made up of primitives. However Gson will trivially handle objects, collections of objects etc. Life gets a little more complex when using generics etc., but for your example above I would expect Gson to work with little trouble.

该对象(顾名思义)由基元组成。然而,Gson 将微不足道地处理对象、对象集合等。使用泛型等时,生活会变得更加复杂,但是对于上面的示例,我希望 Gson 能够轻松工作。

回答by Jayesh

Using Gson to convert to Json using Gson at client side.

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

Sending String array.

发送字符串数组。

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

Sending Array of User Defined Type.

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

        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);     

Using Gson at Server Side to read Data.

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

For Primitive Types.

对于原始类型。

            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);
    }

For User Defined Object

对于用户定义的对象

    String recipientInfos = req.getParameter("recipientInfoStringFormat");

    Gson gson = new Gson();
    RecipientInfo[] ri = gson.fromJson(recipientInfos, RecipientInfo[].class);  

回答by Jay

You can use Hymanson also.

您也可以使用Hyman逊。

    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();

} 

and vice versa

反之亦然

    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();

}

for using Hymanson add this dependency to your POM.xml

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

<repositories>
<repository>
    <id>codehaus</id>
    <url>http://repository.codehaus.org/org/codehaus</url>
</repository>
</repositories>

<dependencies>
<dependency>
    <groupId>org.codehaus.Hymanson</groupId>
    <artifactId>Hymanson-mapper-asl</artifactId>
    <version>1.8.5</version>
</dependency>
</dependencies>