I want to create JSON , format is like
"header":
{
"b":"aaaa",
"c":"00",
"d":"zzzzz",
"e": "0"
},
"Body":
{
"g":
[
{
"h": "sss",
"i": "vvvv",
"j": "11111"
},
{
"h": "wwww",
"i": "ddddd",
"j": "0000"
},
{
"h": "eeeee",
"i": "asd开发者_运维百科f"
}
]
}
I want to create this JSON with the help of GSON.
The target JSON example in the original question is invalid. JSON must start with either '[' or '{'. If the invalid JSON in the original question is wrapped in '{' and '}', then it is a valid JSON object. (It's easy to use http://jsonlint.com to validate JSON.) Assuming then that such a JSON object is the target data structure, following is an example of using a matching Java data structure with Gson to generate the JSON.
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Header header = new Header("aaaa", "00", "zzzzz", "0");
List<Gs> g = new ArrayList<Gs>();
g.add(new Gs("sss", "vvvv", "11111"));
g.add(new Gs("wwww", "ddddd", "0000"));
g.add(new Gs("eeeee", "asdf", null));
Body body = new Body(g);
Message message = new Message(header, body);
System.out.println(new Gson().toJson(message));
}
}
class Message
{
Header header;
Body Body;
Message(Header header, Body body)
{ this.header = header; this.Body = body; }
}
class Header
{
String b;
String c;
String d;
String e;
Header(String b, String c, String d, String e)
{ this.b = b; this.c = c; this.d = d; this.e = e; }
}
class Body
{
List<Gs> g;
Body(List<Gs> g)
{ this.g = g; }
}
class Gs
{
String h;
String i;
String j;
Gs(String h, String i, String j)
{ this.h = h; this.i = i; this.j = j; }
}
精彩评论