将Java对象转换为Json,反之亦然? [英] Convert Java Object to Json and Vice versa?

查看:100
本文介绍了将Java对象转换为Json,反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道JSON对象不过是String.

I know that JSON object is nothing but the String.

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

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

示例:

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发送... 如果没有,另一种替代方法是什么?

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

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

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

谢谢

推荐答案

我得到了答案,但谢谢您的答复.

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

反向

 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

就这样.谢谢

这篇关于将Java对象转换为Json,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆