如何用GSON创建JSONArray [英] How to create a JSONArray with GSON

查看:138
本文介绍了如何用GSON创建JSONArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我需要创建一个JSONArray类型的GSON类

  {
message :[
msg 1,
msg 2,
msg 3
],
asec:[
asec 1 ,
asec 2,
asec 3
]
}

我知道如何在GSON中创建具有键值的JSONArray,例如:

  [
{
message1:msg 1,
asc:asc 1
},
{
message1:msg 2 ,
asc:asc 2
},
{
message1:msg 3,
asc:asc 3






$ b但是我不知道如何创建JSONArray类型可以任何一个帮助我

解决方案



  public class JsonStructure {
public String [] message;
public String [] asec;
}

使用它:

  JsonStructure json = new JsonStructure(); 
json.message = new String [] {msg 1,msg 2,msg 3};
json.asec = new String [] {asec 1,asec 2,asec 3};
Gson gson = new Gson();
字符串输出= gson.toJson(json);
//从字符串转换
JsonStructure fromString = gson.fromJson(output,JsonStructure.class);

有关Google gson的更多详细信息,请查看 https://sites.google.com/site/gson/gson-user-guide


Hi in my project i need to create a JSONArray type with the GSON class

    {
  "message": [
    "msg 1",
    "msg 2",
    "msg 3"
  ],
  "asec": [
    "asec 1",
    "asec 2",
    "asec 3"
  ]
}

I know how to create JSONArray with key value in GSON for eg:

  [
  {
    "message1": "msg 1",
    "asc": "asc 1"
  },
  {
    "message1": "msg 2",
    "asc": "asc 2"
  },
  {
    "message1": "msg 3",
    "asc": "asc 3"
  }
]

But i dont know how to create JSONArray type can any one help me

解决方案

the class:

public class JsonStructure{
    public String[] message;
    public String[] asec;
}

using it:

JsonStructure json = new JsonStructure();
json.message = new String[]{"msg 1", "msg 2", "msg 3"};
json.asec = new String[]{"asec 1", "asec 2", "asec 3"};
Gson gson = new Gson();
String output = gson.toJson(json);
//convert from string
JsonStructure fromString = gson.fromJson(output, JsonStructure.class);

For more details on Google's gson please take a look at https://sites.google.com/site/gson/gson-user-guide

这篇关于如何用GSON创建JSONArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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