简体   繁体   English

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

[英]Convert Java Object to Json and Vice versa?

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. 我的问题是我有一个Object of Object,我想把它转换成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 API available, but I dont know how to use it and or in other efficient way. 据我所知,有Gson API可用,但我不知道如何使用它或以其他有效的方式。

Thank you 谢谢

Not sure what the problem with Gson is. 不确定Gson的问题是什么。 From the doc : 来自doc

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能够轻松地处理。

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

You can use jackson also. 你也可以使用杰克逊。

    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 jackson add this dependency to your POM.xml 使用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>

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 就是它。谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Spring Controller中将JSON转换为Java对象,反之亦然? - How to convert a JSON to java object and vice versa in spring controller? 无法将Zookeeper对象转换为json,反之亦然 - cannot convert a zookeeper object to json and vice versa 将带有嵌入对象的 Java 对象转换为带有属性列表和值列表的 JSON,反之亦然 - Convert Java object with embedded objects to a JSON with list of attributes and list of values and vice versa 在android'java'中如何将Bitmap对象转换为Image对象,反之亦然 - How convert Bitmap Object to Image Object and vice versa in android 'java' 使用jaxb将Java对象转换为xml,反之亦然(将其转换为元组和非元组) - convert java object using jaxb to xml and vice versa (marshal and unmarshal) Java:我可以将对象列表转换为String []列表,反之亦然吗? - Java: Can I convert List of Object to List of String[] and vice versa? 将深层嵌套的json转换为java对象,反之亦然 - Converting deeply nested json to java object and vice versa 如何将 POJO 转换为 JSON,反之亦然? - How to convert POJO to JSON and vice versa? 将 JSON 转换为单行字符串,反之亦然 - Convert JSON to a single line String and vice versa 如何转换ArrayList <object> 转换为字符串,反之亦然 - How to convert ArrayList<object> to String and vice versa
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM