Reputation: 165
So I'm looking to add a lot of users to a group messaging app that allows http post requests and I'm going to try to use the file upload function to read from a JSON but I'm a little confused as to how to write this in java:
{
"members": [
{
"nickname": "Mom",
"user_id": "1234567890",
"guid": "GUID-1"
},
{
"nickname": "Dad",
"phone_number": "+1 2123001234",
"guid": "GUID-2"
},
{
"nickname": "Jane",
"email": "[email protected]",
"guid": "GUID-3"
}
]
}
This is an exmaple of the JSON file that I need to write to, can someone explain how to write that in Java? (It would need nickname & phone_number fields, only those two per person) Thanks!
EDIT 1: Sorry, wasn't clear. I need to use Java to produce a file with these contents.
Upvotes: 0
Views: 90
Reputation: 754
Treat {}
as classes and []
as arrays:
import com.google.gson.annotations.SerializedName;
public class Message {
@SerializedName("members")
private List<Member> members;
...
public class Member {
@SerializedName("nickname")
private String nickname;
@SerializedName("user_id")
private String userId;
@SerializedName("guid")
private String guid;
...
To transform to JSON:
Message msg;
...
String jsonResult = new Gson().toJson(msg);
To get back from JSON:
Message msg = new Gson().fromJson(jsonStr, Message.class);
User guide: https://sites.google.com/site/gson/gson-user-guide
Upvotes: 1
Reputation: 3256
Try try https://github.com/google/gson
http://www.studytrails.com/java/json/java-google-json-parse-json-to-java.jsp
Example:
import com.google.gson.Gson;
public class JavaToJsonAndBack {
public static void main(String[] args) {
Albums albums = new Albums();
albums.title = "Free Music Archive - Albums";
albums.message = "";
albums.total = "11259";
albums.total_pages = 2252;
albums.page = 1;
albums.limit = "5";
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
System.out.println(gson.toJson(albums));
}
}
This is how the resulting JSON looks like
{"title":"Free Music Archive - Albums","message":"","errors":[],
"total":"11259","total_pages":2252,"page":1,"limit":"5"}
Upvotes: 3