Build dynamic JSON - java

I'm trying to build dynamic json request in java to send to my c++ server. I'm using the GSON library.
This is my json example:
{
"nodes": {
"12131231231231241": {
"gToken": {
"token": "AABBCCDDEEFF99001122334455667788"
},
"objects": {
"WATER_CONTROL_1": "0"
}
},
"7682642342432423": {
"userAuthentication": {
"userEmail": "user#mail.com",
"userPassword": "userPassword"
},
"objects": {
"LIGHT_1_CONTROL": "1"
}
}
}
}
If you can see the nodes object is dynamic. Inside him i can have a lot of items (in the example i put two, representing by 12131231231231241 and 7682642342432423). Inside each item the authentication method can be different (by token, by email/password) and inside objects item i can have a lot of different dynamic items too.
The part to send to my c++ server, parse the JSON and do the all validations (authetication for example) is already done and working (i test this json example inside c++ string, encode to json and do the parse, get the all items,etc).
So my problem is to build my class to send the request with some struct to corresponding to this dynamic json.
I already implement some other class to send json to my server and its work because i already know the json expected and on other cases the json have a static/fixed content.
My class for this dynamic json:
public class MonitorControlGetRequestArgs implements SerializableJSON {
Nodes nodes;
public MonitorControlGetRequestArgs() {
nodes = new Nodes();
}
static class Nodes{
public Nodes(){
}
}
public static MonitorControlGetRequestArgs fromStringJson(String data){
try {
Gson gson = new Gson();
return gson.fromJson(data, MonitorControlGetRequestArgs.class);
}
catch(Exception e){
return null;
}
}
public static MonitorControlGetRequestArgs fromBytesJson(byte[] data){
if (data == null)
return null;
try {
String str = new String(data, "utf-8");
return fromStringJson(str);
}
catch (Exception e) {
return null;
}
}
#Override
public String toJsonString(){
try{
Gson gson = new Gson();
return gson.toJson(this);
}
catch(Exception e){
return null;
}
}
#Override
public byte[] toJsonBytes(){
try {
return this.toJsonString().getBytes("utf-8");
}
catch (Exception e){
return null;
}
}
}
I create a static class Nodes empty to show you. In my server c++ i receive the item nodes in json format, but now i have a lot of doubts how to build the struct inside nodes to corresponding to my dynamic json.
I hope you understand my doubts. If you don't understand something tell to me.
EDIT 1 - (try to use the example of Andriy Rymar)
I try to simulate this json:
{
"nodes": {
"1317055040393017962": {
"userAuthentication": {
"userEmail": "rr#rr.com",
"userPassword": "rr123"
}
}
}
}
My request class:
public class MonitorControlGetRequestArgs implements SerializableJSON
{
private final static String nodeTemplate = "\"%s\":%s";
List nodes = new ArrayList<>();
public MonitorControlGetRequestArgs(UserAuthentication userAuthentication)
{
JsonData jsonData = new JsonData();
jsonData.addNode(new Node("1317055040393017962", new NodeObject(userAuthentication)));
}
static class Node
{
private final String nodeName;
private final Object nodeBody;
public Node(String nodeName, Object nodeBody) {
this.nodeName = nodeName;
this.nodeBody = nodeBody;
}
public String getNodeName() {
return nodeName;
}
public Object getNodeBody() {
return nodeBody;
}
}
static class JsonData {
List<Node> nodes = new ArrayList<>();
public void addNode(Node node){
nodes.add(node);
}
}
static class NodeObject
{
UserAuthentication userAuthentication;
public NodeObject(UserAuthentication userAuthentication)
{
this.userAuthentication = userAuthentication;
}
}
public static MonitorControlGetRequestArgs fromStringJson(String data)
{
try
{
Gson gson = new Gson();
return gson.fromJson(data, MonitorControlGetRequestArgs.class);
}
catch(Exception e)
{
return null;
}
}
public static MonitorControlGetRequestArgs fromBytesJson(byte[] data)
{
if (data == null) return null;
try
{
String str = new String(data, "utf-8");
return fromStringJson(str);
}
catch (Exception e)
{
return null;
}
}
#Override
public String toJsonString()
{
try
{
Gson gson = new Gson();
return gson.toJson(this);
}
catch(Exception e)
{
return null;
}
}
#Override
public byte[] toJsonBytes()
{
try
{
return this.toJsonString().getBytes("utf-8");
}
catch (Exception e)
{
return null;
}
}
}
EDIT 2
I will try to explain better,i believe I was not totally explicit. My application java is a REST application that send json to my c++ server. In my server i receive the json, i do the parse, i do the validation, the operations, etc and return back to my java client the response in json too.
For example, imagine that my json request body (to create a new user for example) is something like this:
{
"userInformation": {
"name": "user name",
"age": 33
}
}
For this i don't have any doubts how to do (i already implement a lot of requests very similar). I can create a static class like this:
static class UserInfo
{
String name;
String age;
public UserInfo(String name, String age)
{
this.name = name;
this.age = age;
}
}
And inside a request class (very similar to a class like i copy before - MonitorControlGetRequestArgs) i create a new instance to my UserInfo
UserInfo userInformation = new UserInfo (name, age)
In this case its easy because the request json body is static. I already now that i have a userInformation section and inside i have a name and age. To create a list with userInfo (to create multiple users at same time for example) i already implement things like this.
But now, for this specific case i have this json:
{
"nodes": {
"12131231231231241": {
"gToken": {
"token": "AABBCCDDEEFF99001122334455667788"
},
"objects": {
"WATER_CONTROL_1": "0"
}
},
"7682642342432423": {
"userAuthentication": {
"userEmail": "user#mail.com",
"userPassword": "userPassword"
},
"objects": {
"LIGHT_1_CONTROL": "1"
"LIGHT_3_CONTROL": "0"
}
}
}
}
So in this case i have some problems. In these example i put two items (12131231231231241,7682642342432423) but the user can send more (3,4,5,50,100). In the other hand inside nodes i have two sections (12131231231231241,7682642342432423) but this numbers are some ids that i use in my app and i never know that ids the user will put. In last example ( userInformation ) its simple because i create a userInformation section because i already know that the user always put this section, it is static. In these new json request i dont know, because i never now what value he put, i only know that is a string. The authentication method i dont have problems to create. But other problem that i expected to have is in objects section, because the user can put to a lot of objects and i never know what is the key (in userInformation i know that the keys are always the name and age for example and only exits these two keys, i these new case i dont know what is the keys and what are the number of pair of keys/values he put).
EDIT 3 -
I implement this code and i could almost produce all the structure I need. I'm using the gson same.
Nodes nodes;
public MonitorControlGetRequestArgs(String userEmail, String userPassword, Map <String,String> objects)
{
nodes = new Nodes(userEmail, userPassword, objects);
}
static class Nodes
{
AuthenticationMethod authenticationMethod;
Map <String,String> objects;
public Nodes(String userEmail, String userPassword, Map <String,String> objects)
{
authenticationMethod = new AuthenticationMethod(userEmail, userPassword);
this.objects = objects;
}
}
The result json:
{
"nodes": {
"authenticationMethod": {
"userAuthentication": {
"userEmail": "user#mail.com",
"userPassword": "userPassword"
}
},
"objects": {
"aa": "aaaaaaaaaaaaa",
"bbbbbbb": "bbbbb",
"ccdd": "ccddccdd"
}
}
}
Know i only need to add some struct to support this json:
{
"nodes": {
"7682642342432423": {
"authenticationMethod": {
"userAuthentication": {
"userEmail": "user#mail.com",
"userPassword": "userPassword"
}
},
"objects": {
"0": "Hammersmith & City",
"1": "Circle",
"dasd": "dasda"
}
}
}
}
Note: The objects is a map, so i can put the number of objects string/string that i want. Know i need to do something to support the previous json with the 7682642342432423, 12131231231231241, etc, etc..
EDIT 4 - final
Map <String, Obj> nodes;
public MonitorControlGetRequestArgs(Map <String, Obj> nodes)
{
this.nodes = nodes;
}
static class Obj
{
AuthenticationMethod authenticationMethod;
Map <String,String> objects;
public Obj(String userEmail, String userPassword, Map <String,String> objects)
{
authenticationMethod = new AuthenticationMethod(userEmail, userPassword);
this.objects = objects;
}
}
Json that arrive in my server (like i want)
{
"nodes": {
"12131231231231241": {
"authenticationMethod": {
"userAuthentication": {
"userEmail": "user#mail.com",
"userPassword": "userPassword"
}
},
"objects": {
"aa": "aaaaaaaaaaaaa",
"bbbbbbb": "bbbbb",
"ccdd": "ccddccdd"
}
},
"777777777777777": {
"authenticationMethod": {
"userAuthentication": {
"userEmail": "user#mail.com",
"userPassword": "userPassword"
}
},
"objects": {
"aa": "aaaaaaaaaaaaa",
"bbbbbbb": "bbbbb",
"ccdd": "ccddccdd"
}
}
}
}

Here is improved code from previous example that is more flexible and has better serialization mechanism :
public class ForTestApplication {
public static void main(String[] args) {
NodeArray jsonContainer = new NodeArray(
new Node("nodes", new NodeArray(
new Node("12131231231231241", new NodeArray(
new Node("gToken",
new Node("token", "AABBCCDDEEFF99001122334455667788")),
new Node("objects", new NodeArray(
new Node("WATER_CONTROL_1", "0"),
new Node("WATER_CONTROL_2", "1")
)))),
new Node("7682642342432423", new NodeArray(
new Node("userAuthentication", new NodeArray(
new Node("userEmail","user#mail.com"),
new Node("userPassword","userPassword")
)),
new Node("objects", new NodeArray(
new Node("WATER_CONTROL_1", "0"),
new Node("WATER_CONTROL_2", "1")
))
))
)));
System.out.println(jsonContainer.toJSONString());
}
}
class NodeArray {
private static final String NODE_TEMPLATE = "\"%s\":%s";
private static final Gson gson = new Gson();
private List<Node> nodes = new ArrayList<>();
public NodeArray(Node... nodes){
addNode(nodes);
}
public void addNode(Node... node){
nodes.addAll(Arrays.asList(node));
}
public String toJSONString() {
return nodes.stream()
.map(node -> String.format(NODE_TEMPLATE, node.getNodeName(), getNodeBodyAsJSON(node)))
.collect(Collectors.joining(",", "{", "}"));
}
private String getNodeBodyAsJSON(Node node) {
if (node.getNodeBody() instanceof NodeArray) {
return ((NodeArray) node.getNodeBody()).toJSONString();
}
return gson.toJson(node.getNodeBody());
}
}
class Node {
private final String nodeName;
private final Object nodeBody;
public Node(String nodeName, Object nodeBody) {
this.nodeName = nodeName;
this.nodeBody = nodeBody;
}
public String getNodeName() {
return nodeName;
}
public Object getNodeBody() {
return nodeBody;
}
}
The output of such application is :
{"nodes":{"12131231231231241":{"gToken":{"nodeName":"token","nodeBody":"AABBCCDDEEFF99001122334455667788"},"objects":{"WATER_CONTROL_1":"0","WATER_CONTROL_2":"1"}},"7682642342432423":{"userAuthentication":{"userEmail":"user#mail.com","userPassword":"userPassword"},"objects":{"WATER_CONTROL_1":"0","WATER_CONTROL_2":"1"}}}}
Pretty view is :
NOTICE : this example use constructors to build complex structures but I highly recommend to use builder pattern for such case. Code will be clearer and better.

Here is example of what you need using Gson. But if you would like to use something else, for example OrgJson then the code will be more clear and without String templates.
public class ForTestApplication {
private final static String nodeTemplate = "\"%s\":%s";
public static void main(String[] args) {
JsonData jsonData = new JsonData();
jsonData.addNode(new Node("user-1", new TestObject(62, "James", "Gosling")));
jsonData.addNode(new Node("user-2", new TestObject(53, "James", "Hetfield")));
System.out.println(jsonData.toJSONStirng());
}
static class JsonData {
List<Node> nodes = new ArrayList<>();
public void addNode(Node node){
nodes.add(node);
}
public String toJSONStirng() {
Gson gson = new Gson();
return nodes.stream()
.map(node -> String.format(nodeTemplate, node.getNodeName(), gson.toJson(node.getNodeBody())))
.collect(Collectors.joining(",", "{", "}"));
}
}
static class Node {
private final String nodeName;
private final Object nodeBody;
public Node(String nodeName, Object nodeBody) {
this.nodeName = nodeName;
this.nodeBody = nodeBody;
}
public String getNodeName() {
return nodeName;
}
public Object getNodeBody() {
return nodeBody;
}
}
static class TestObject {
private int age;
private String firstName;
private String lastName;
public TestObject(int age, String firstName, String lastName) {
this.age = age;
this.firstName = firstName;
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
}
Output :
{"user-1":{"age":62,"firstName":"James","lastName":"Gosling"},"user-2":{"age":53,"firstName":"James","lastName":"Hetfield"}}
Pretty view :

Related

Converting a string to list of Objects in java

I have this string:
[{
"expectedInput": "hello",
"expectedResponse": "how can i help you?"
},
{
"expectedInput": "need sip support",
"expectedResponse": "ok, let me check "
}
]
and i want to convert into List of Objects i.e List<MessageDetails>
where MessageDetails.class is
public class MessageDetails {
private String expectedInput;
private String expectedResponse;
public String getExpectedInput() {
return expectedInput;
}
public void setExpectedInput(String expectedInput) {
this.expectedInput = expectedInput;
}
public String getExpectedResponse() {
return expectedResponse;
}
public void setExpectedResponse(String expectedResponse) {
this.expectedResponse = expectedResponse;
}
}
You can easily do it with the help of Jackson:
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(source);
List<MessageDetails> list = Arrays.asList(mapper.treeToValue(node, MessageDetails[].class));
for (MessageDetails messageDetail : list) {
System.out.println(messageDetail.getExpectedInput() + ": " + messageDetail.getExpectedResponse());
}

Deserializing JSON using spring boot into a POJO with a list of generic objects

I'm trying to deserialize a JSON result of a search API. The search API (and I have simplified here) has a main object with metadata about the search and then has a list of whatever the searched object is. I'm trying to achieve this using a list of generic objects
I have tested these classes without the and everything works exactly as I would want it to.
TestSearch.java
public class TestSearch<T> {
private String count;
private List<T> results;
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public List<T> getResults() {
return results;
}
public void setResults(List<T> results) {
this.results = results;
}
}
TestResult.java
public class TestResult {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
TestController.java
#RequestMapping("/test/json")
public String testGetJson() {
return "{\"count\":3,\"results\":[{\"name\":\"result 1\",\"description\":\"this is the first result\",\"extra\":\"property\"},{\"name\":\"result 2\",\"description\":\"tqbf\"},{\"name\":\"result 3\",\"description\":\"jotlz\"}]}";
}
#RequestMapping("/test/testserialize")
public List<TestResult> testSerialize() {
TestSearch<TestResult> testSearch = new RestTemplate().getForObject("http://localhost:8957/test/json", new TestSearch<TestResult>().getClass());
List<TestResult> results = testSearch.getResults();
results.forEach(result -> {
result.setName("new value");
});
return results;
}
JSON (just to make things more readable)
{
"count": 3,
"results": [
{
"name": "result 1",
"description": "this is the first result",
"extra": "property"
},
{
"name": "result 2",
"description": "tqbf"
},
{
"name": "result 3",
"description": "jotlz"
}
]
}
After calling the endpoint /test/testserialize my application throws this error
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast
to com.testapp.entity.TestResult
Now, if I go back and update the TestSearch class to:
public class TestSearch {
private String count;
private List<TestResult> results;
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public List<TestResult> getResults() {
return results;
}
public void setResults(List<TestResult> results) {
this.results = results;
}
}
I get the results I'm expecting:
[
{
"name": "new value",
"description": "this is the first result"
},
{
"name": "new value",
"description": "tqbf"
},
{
"name": "new value",
"description": "jotlz"
}
]
The getClass() method inside of the getForObject function does not see the type
To solve this, use a ParameterizedTypeReference
TestSearch<TestResult> testSearch = new RestTemplate().exchange(
"http://localhost:8957/test/json",
HttpMethod.GET,
null,
new ParameterizedTypeReference<TestSearch<TestResult>>() {}).getBody();
I finally tracked down a solution that happens to be 6 years old:
Generics with Spring RESTTemplate
You need to create a TypeReference object for each generic type you use and use that for deserialization. For example,
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = new HashMap<String, Object>();
// convert JSON string to Map
map = mapper.readValue(json, new TypeReference<Map<String, String>>(){});
In your case you will have to create the type reference for
public List<T> getResults()
Please let me know if you need additional help in it.

Gson- Parsing a JSON array of JSON objects to ArrayList<org.json.JSONObject>

I have a JSON string like this:
{
"r": [
{
"pic": "1.jpg",
"name": "Name1"
},
{
"pic": "2.jpg",
"name": "Name2"
},
{
"pic": "3.jpg",
"name": "Name3"
}
]
}
I want to parse to this POJO model:
public class Catalog {
#SerializedName("r")
#Expose
private List<JSONObject> r = new ArrayList<JSONObject>();
public List<JSONObject> getR() {
return r;
}
public void setR(List<JSONObject> r) {
this.r = r;
}
}
I am parsing this way:
Catalog cat = new Gson().fromJson(jsonString,Catalog.class);
But finally am getting this json
{
"r": [
{
"nameValuePairs": {}
},
{
"nameValuePairs": {}
},
{
"nameValuePairs": {}
}
]
}
Please note that I don't want to use com.google.gson.JsonObject.
I want to use org.json.JSONObject. How to achieve this because almost all of my code uses it?
As it was already mentioned in other answer and comments, you probably might not really want to use org.json.JSONObject for several reasons. But if it's a must for you, you just have to create your org.json.JSONObject-aware Gson instance.
final class JSONObjectJsonDeserializer
implements JsonDeserializer<JSONObject> {
// The implementation is fully thread-safe and can be instantiated once
private static final JsonDeserializer<JSONObject> jsonObjectJsonDeserializer = new JSONObjectJsonDeserializer();
// Type tokens are immutable values and therefore can be considered constants (and final) and thread-safe as well
private static final TypeToken<Map<String, Object>> mapStringToObjectTypeToken = new TypeToken<Map<String, Object>>() {
};
private JSONObjectJsonDeserializer() {
}
static JsonDeserializer<JSONObject> getJsonObjectJsonDeserializer() {
return jsonObjectJsonDeserializer;
}
#Override
public JSONObject deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) {
// Convert the input jsonElement as if it were a Map<String, Object> (a generic representation for JSON objectS)
final Map<String, Object> map = context.deserialize(jsonElement, mapStringToObjectTypeToken.getType());
// And forward the map to the JSONObject constructor - it seems to accept it nice
return new JSONObject(map);
}
}
Gson is designed thread-safe and does not need to be instantiated every time serialization or deserialization is necessary:
private static final Gson gson = new GsonBuilder()
.registerTypeAdapter(JSONObject.class, getJsonObjectJsonDeserializer())
.create();
And finally:
final Catalog catalog = gson.fromJson(jsonString, Catalog.class);
out.println(catalog.getR());
with the following result:
[{"name":"Name1","pic":"1.jpg"}, {"name":"Name2","pic":"2.jpg"}, {"name":"Name3","pic":"3.jpg"}]
Anyway, I would suggest you to redesign your mappings model.
I think you don't need JSONObject.
Try this
// is wrapped class for serialized json.
public class JsonExample
{
List<Catalog> r;
}
public class Catalog {
private String pic;
private String name;
public String getPic() {
return pic;
}
public String getName() {
return name;
}
}
JsonExample example = new Gson().fromJson(json, JsonExample.class);
Additional - using JSONObject
JSONObject obj = new JSONObject(json);
JSONArray arr = obj.getJSONArray("r");
List<Catalog> cataList = new ArrayList<>();
for(int i = 0 ; i < arr.length() ; ++i)
{
cataList.add(new Catalog(arr.getJSONObject(i)));
}
public class Catalog {
private String pic;
private String name;
public Catalog(JSONObject obj) throws JSONException
{
pic = obj.getString("pic");
name = obj.getString("name");
}
public String getPic() {
return pic;
}
public String getName() {
return name;
}
}
I think in your case, usage of gson library is not required at all.
Only org.json can solve the entire problem.
E.g.:
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONArray("r");
List<JSONObject> jsonList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonList.add(jsonArray.getJSONObject(i));
}
Catalog catalog = new Catalog();
catalog.setR(jsonList);

Deserialize a JSON containing a list of objects using Gson

I'm trying to deserialize a JSON which containes a String and a list of objects in my Spring web application.
JSON
[
{
"jsonrpc":"2.0",
"result":[
{
"event":{
"id":"27809810",
"name":"Spezia v Trapani",
"countryCode":"IT",
"timezone":"Europe/London",
"openDate":"2016-05-28T16:30:00.000Z"
},
"marketCount":13
},
{
"event":{
"id":"27811083",
"name":"Torino U19 v Atalanta U19",
"countryCode":"IT",
"timezone":"Europe/London",
"openDate":"2016-05-29T16:15:00.000Z"
},
"marketCount":18
},
...
]
My classes are:
ListEventsResponse class
public class ListEventsResponse {
private String jsonrpc;
private List<ListEventsResult> result;
public ListEventsResponse() { }
public String getJsonrpc() {
return jsonrpc;
}
public void setJsonrpc(String jsonrpc) {
this.jsonrpc = jsonrpc;
}
public List<ListEventsResult> getResult() {
return result;
}
public void setResult(List<ListEventsResult> result) {
this.result = result;
}
}
ListEventsResult class
public class ListEventsResult {
private Event event;
private int marketCount;
public ListEventsResult() { }
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
public int getMarketCount() {
return marketCount;
}
public void setMarketCount(int marketCount) {
this.marketCount = marketCount;
}
}
I have also Event class, composed by 5 String (id, name, etc.).
Controller
[...]
ListEventsResponse listEvents = new Gson().fromJson(response.toString(), ListEventsResponse.class);
List<ListEventsResult> eventsList = listEvents.getResult();
return new ModelAndView("page", "eventsList", eventsList);
My .jsp page
[...]
<c:forEach items="${eventsList}" var="listEventsResult">
Match: <c:out value="${listEventsResult.name}"/>
</c:forEach>
[...]
My code runs and doesn't give any error, but no match is shown on my page, in fact listEvents doesn't contains any object.
I can't understand how to deserialize properly the list of objects, so my question is: which logic is behind the deserialization of a json which contains a list of objects?
I post my code just to explain better my problem.
As you have a Json Array as response , you need to deserialize like below
Gson gson = new Gson();
Type type = new TypeToken<List<ListEventsResponse>>(){}.getType();
List<ListEventsResponse> events = (List<ListEventsResponse>) gson.fromJson(response.toString(), type);

GSON getting arrays [duplicate]

I have a basic JSON with all data contained in an array. One would think that it would be simple to retreive a value out of the array, but after multiple hours of trying every different method of parsing I could think of I'm completely lost. Any help would be greatly appreciated. Sorry for the horrid wording of this question.
I know I've attempted reading the JSON as an object using JsonReader and then parsing for the ID field. That would be my latest attempt, the code for the other attempts has already been deleted I'm afraid and I can't provide much information on said attempts
JsonReader reader = new JsonReader(new FileReader(Constants.VersJson));
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
reader.beginArray();
if (name.equals("id")) {
System.out.println(reader.nextString());
Below I'll include a snippet of the JSON Array.
"versions": [
{
"id": "2.7",
"time": "2012-10-25T15:00:00+02:00",
"releaseTime": "2013-10-25T15:00:00+02:00",
"type": "Release"
},
{
"id": "2.6.4",
"time": "2011-12-2T14:01:07+02:00",
"releaseTime": "2013-12-2T14:01:07+02:00",
"type": "Develop"
},
{
"id": "2.5",
"time": "2010-11-24T21:05:00+02:00",
"releaseTime": "2013-11-25T01:04:05+02:00",
"type": "Develop"
Your json format is not correct which you have posted here
correct it for example
{
"versions":[
{
"id":"2.7",
"time":"2012-10-25T15:00:00+02:00",
"releaseTime":"2013-10-25T15:00:00+02:00",
"type":"Release"
},
{
"id":"2.6.4",
"time":"2011-12-2T14:01:07+02:00",
"releaseTime":"2013-12-2T14:01:07+02:00",
"type":"Develop"
}
]
}
First Define Classes you will get everything
public class Version {
private List<Versions> versions;
public List<Versions> getVersions() {
return versions;
}
public void setVersions(List<Versions> versions) {
this.versions = versions;
}
#Override
public String toString() {
return "Version [versions=" + versions + "]";
}
}
public class Versions {
private String id;
private String time;
private String releaseTime;
private String type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getReleaseTime() {
return releaseTime;
}
public void setReleaseTime(String releaseTime) {
this.releaseTime = releaseTime;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return "Versions [id=" + id + ", time=" + time + ", releaseTime="
+ releaseTime + ", type=" + type + "]";
}
}
Finally you can parse the JSON as like here
JsonReader reader = new JsonReader(new FileReader(Constants.VersJson));
Gson gson = new Gson();
Version version = gson.fromJson(reader, Version.class);
i have also faced json array parsing using gson here is my code solved it
this is my reader class functions
JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(myFile)));
System.out.println( reader);
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray jArray = parser.parse(reader).getAsJsonArray();
ArrayList<JsonOperations> lcs = new ArrayList<JsonOperations>();
for(JsonElement obj : jArray )
{
JsonOperations cse = gson.fromJson( obj , JsonOperations.class);
lcs.add(cse);
}
for ( JsonOperations tUser : lcs)
{
System.out.println(tUser);
}
my json operation class is
public class JsonOperations {
String match_id, pool_name, team1_name, team1_image, team2_name,
team2_image, match_date, match_country, match_venue, predicted;
public JsonOperations() {
}
public JsonOperations(String match_id, String pool_name, String team1_name,
String team1_image, String team2_name, String team2_image,
String match_date, String match_country, String match_venue,
String predicted) {
this.match_id = match_id;
this.pool_name = pool_name;
this.team1_name = team1_name;
this.team1_image = team1_image;
this.team2_name = team2_name;
this.team2_image = team2_image;
this.match_date = match_date;
this.match_country = match_country;
this.match_venue = match_venue;
this.predicted = predicted;
}
public void set_team1(String team1_name) {
this.team1_name = team1_name;
}
public void set_team2(String team2_name) {
this.team2_name = team2_name;
}
public String get_team1() {
return team1_name;
}
public String get_team2() {
return team2_name;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return this.get_team1() + this.get_team2();
}
}

Categories

Resources