使用Gson和JsonObject来格式化和解析数据 [英] Using Gson and JsonObject to format and parse data

查看:221
本文介绍了使用Gson和JsonObject来格式化和解析数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 JsonObject Gson 来格式化我需要以字符串形式发送的数据然后在其他地方检索并解析它。
这是我的简单代码不工作:

pre $ public static void main(String [] args)
{

Gson g = new Gson();
Gson listG = new Gson();
ArrayList< String> l = new ArrayList< String>();
l.add(abcd);
l.add(efgh);
l.add(ijkl);

String list = listG.toJson(l);

JsonObject jObject = new JsonObject();
jObject.addProperty(command,1);
jObject.addProperty(message,this is a test message);
jObject.addProperty(list,list);

String toSend = g.toJson(jObject);
System.out.println(toSend);

Gson rec = new Gson();
JsonObject newObj = rec.fromJson(toSend,JsonObject.class);
System.out.println(newObj); // newObj中没有任何内容


}

什么是我在这里做错了?

解决方案

您应该使用:

<$ p $ jsonObject newObj = new JsonParser()。parse(toSend).getAsJsonObject();

有很多调用,但要点是使用 JsonParser 课程。


I am using JsonObject and Gson to format the data i need to send in the form of String and then retrieve and parse it somewhere else. This is my simple code which is not working:

public static void main(String[] args) 
{

    Gson g = new Gson();
    Gson listG = new Gson();
    ArrayList<String> l= new ArrayList<String>();
    l.add("abcd");
    l.add("efgh");
    l.add("ijkl");

    String list = listG.toJson(l);

    JsonObject jObject = new JsonObject();
    jObject.addProperty("command" , 1);
    jObject.addProperty("message" , "this is a test message");
    jObject.addProperty("list" , list);

    String toSend = g.toJson(jObject);
    System.out.println(toSend);  

    Gson rec = new Gson();
    JsonObject newObj = rec.fromJson(toSend, JsonObject.class);
    System.out.println(newObj);  // getting nothing in newObj


}

What am i doing wrong here?

解决方案

You should use:

JsonObject newObj = new JsonParser().parse(toSend).getAsJsonObject();

Lots of calls in there, but the gist is to use the JsonParser class.

这篇关于使用Gson和JsonObject来格式化和解析数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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