how to add new data to existing json file in java - java

i'm trying to add new data to existing json file that named question.json but it's not working! it create a new file, can someone help me please!
mycode: i'm using json-simple1.1
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class Main {
public static void writeToJson() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("question", "q3");
ArrayList<String>anss = new ArrayList<>();
anss.add("a1");
anss.add("a2");
anss.add("a3");
anss.add("a4");
JSONArray arr = new JSONArray();
arr.add(anss.get(0));
arr.add(anss.get(1));
arr.add(anss.get(2));
arr.add(anss.get(3));
jsonObject.put("answers",arr);
jsonObject.put("correct_ans", "2");
jsonObject.put("level", "2");
jsonObject.put("team", "animal");
try {
FileWriter file = new FileWriter("json/quetion.json");
file.write(jsonObject.toJSONString());
file.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[]args) {
writeToJson();
}
}
{
"questions":[
{
"question": "q1",
"answers": [
"answer1",
"answer2",
"answer3",
"answer4"
],
"correct_ans": "2",
"level": "1",
"team": "animal"
},
{
"question": "q2",
"answers": [
"answer1",
"answer2",
"answer3",
"answer4"
],
"correct_ans": "1",
"level": "2",
"team": "animal"
}
]
}
this is the json file i want to add what i wrote in the code to this json file but i failed! i need someone to tell me how can i add a new json object like {"question" : "q2" ...} without changing the format of the json file or creating a new json file.

org.json.simple
The structure of your JSON has more levels of nesting than can be observed in your code therefore your result doesn't match.
That's what you have in the JSON:
JSONObject { field : JSONArray [ JSONObject { field : value, field : JSONArray, ... }
I.e. JSONObject which contains a JSONArray which might contain several JSONObjects which in turn contain a JSONArray.
That's how it can be translated into the code (to avoid redundancy logic which for creating a nested JSONObject was extracted into a separate method):
JSONObject root = new JSONObject();
JSONArray questions = new JSONArray();
JSONObject question1 = createQuestion(
"q1", "2", "1", "animal",
"answer1", "answer2", "answer3", "answer4"
);
JSONObject question2 = createQuestion(
"q2", "1", "2", "animal",
"answer1", "answer2", "answer3", "answer4"
);
Collections.addAll(questions, question1, question2);
root.put("questions", questions);
public static JSONObject createQuestion(String questionId,
String correctAnswer,
String level, String team,
String... answers) {
JSONObject question = new JSONObject();
question.put("question", questionId);
JSONArray answersArray = new JSONArray();
Collections.addAll(answersArray, answers);
question.put("answers", answersArray);
question.put("correct_ans", correctAnswer);
question.put("level", level);
question.put("team", team);
return question;
}
That's it.
There's a lot of low-level logic which you can eliminate if you would choose a more mature tool for parsing JSON like Jackson, Gson.
Jackson
Here's an example using Jackson library.
Firstly, let's create two POJO: one representing a single question and another wrapping a list of question. For convince, and also in order to avoid posting boilerplate code, I would use Lombock's.
Question class:
#Builder
#AllArgsConstructor
#Getter
public static class Question {
private String questionId;
private List<String> answers;
private String correctAnswer;
private String level;
private String team;
}
Questions class:
#AllArgsConstructor
#Getter
public static class Questions {
private List<Question> questions;
}
Here's how such objects can be serialized:
Question question3 = Question.builder()
.questionId("q1")
.answers(List.of("answer1", "answer2", "answer3", "answer4"))
.correctAnswer("2")
.level("1")
.team("animal")
.build();
Question question4 = Question.builder()
.questionId("q2")
.answers(List.of("answer1", "answer2", "answer3", "answer4"))
.correctAnswer("1")
.level("2")
.team("animal")
.build();
Questions questions1 = new Questions(List.of(question3, question4));
ObjectMapper mapper = new ObjectMapper();
String json1 = mapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(questions1);
System.out.println(json1);
Output:
{
"questions" : [ {
"questionId" : "q1",
"answers" : [ "answer1", "answer2", "answer3", "answer4" ],
"correctAnswer" : "2",
"level" : "1",
"team" : "animal"
}, {
"questionId" : "q2",
"answers" : [ "answer1", "answer2", "answer3", "answer4" ],
"correctAnswer" : "1",
"level" : "2",
"team" : "animal"
} ]
}

Related

Trouble deserializing JSON into Java objects with GSON

I have been trying to learn GSON, but I am struggling with it. I am trying to deserialize a JSON file into Java objects, using GSON. I have read a million other questions on here, and for the life of me, I can't understand what I'm doing wrong.
Here is my JSON text:
{
"movies": [
{
"name": "The Shawshank Redemption",
"url": "https://parsehub.com/sandbox/moviedetails?movie=The%20Shawshank%20Redemption",
"IMAX": "06:00 PM",
"rating": "9 . 2",
"cast": [
{
"character": "Andy Dufresne",
"actor": "Tim Robbins"
},
{
"character": "Ellis Boyd 'Red' Redding",
"actor": "Morgan Freeman"
},
{
"character": "Warden Norton",
"actor": "Bob Gunton"
},
{
"character": "Heywood",
"actor": "William Sadler"
}
]
},
{
"name": "Schindler's List",
"url": "https://parsehub.com/sandbox/moviedetails?movie=Schindler%27s%20List",
"IMAX": "06:15 PM",
"rating": "8 . 9",
"cast": [
{
"character": "Oskar Schindler",
"actor": "Liam Neeson"
},
{
"character": "Itzhak Stern",
"actor": "Ben Kingsley"
},
{
"character": "Amon Goeth",
"actor": "Ralph Fiennes"
}
]
}
]
}
And here is my Java code:
import com.google.gson.Gson;
import java.io.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Gson gson = new Gson();
Movies[] movies = gson.fromJson(new FileReader("src/main/input.json"), (Type) Movies.class);
System.out.println(movies[0]);
}
class Movies {
String name;
String url;
String IMAX;
String rating;
ArrayList<Cast> cast;
}
class Cast {
ArrayList<CastMember> castMembers;
}
class CastMember{
String character;
String actor;
}
}
When I run this, I get the following error:
Exception in thread "main" java.lang.ClassCastException: class com.Main$Movies cannot be cast to class [Lcom.Main$Movies; (com.Main$Movies and [Lcom.Main$Movies; are in unnamed module of loader 'app')
at com.Main.main(Main.java:13)
The JSON you are deserializing represents an object with a list of objects on it. The Java object you are trying to deserialize to needs to match that.
First, create a new class MovieList.
class MovieList {
List<Movie> movies;
}
Update your Movies class to be called Movie, since it represents a single movie.
class Movie {
String name;
String url;
String IMAX;
String rating;
List<Cast> cast;
}
Now try calling gson.fromJson(...) with the following
MovieList movieList = gson.fromJson(new FileReader("src/main/input.json"), MovieList.class);
System.out.println(movieList.getMovies().get(0));
Try using this
Gson gson = new Gson();
Movies[] movies = gson.fromJson(new JsonReader(new FileReader("src/main/input.json"))),Movies[].class);
or something like
Type listType = new TypeToken<List<Movies>>() {}.getType();
List<Movies> movies = new Gson().fromJson(new JsonReader(new FileReader("src/main/input.json"))), listType);

How to parse JSON String to java object with jackson?

I am currently having trouble trying to parse this VCAP_SERVICES to java objects. I do not quite understand how to structure the POJO to allow it to map the values from the json string. Can someone please help me structure my pojo so that it is aligns with the json string?
I want to create objects for both of the credentials: accessToken... jdbcurl.
VCAP_SERVICES
"VCAP_SERVICES": {
"user-provided": [
{
"credentials": {
"accessTokenUri": "tokenurl",
"apiUrl": "apiurl",
"clientId": "typeofID",
"clientSecret": "secretAf",
"scope": "none"
},
"syslog_drain_url": "",
"volume_mounts": [],
"label": "user-provided",
"name": "OAuth2",
"tags": []
},
{
"credentials": {
"jdbcUrl": "jdbc:oracle:connection[host]:[port]/service",
"spring.datasource.driver-class-name": "oracle.jdbc.OracleDriver",
"spring.datasource.initialize": "false"
},
"syslog_drain_url": "",
"volume_mounts": [],
"label": "user-provided",
"name": "Database",
"tags": []
}
]
Java Class
ObjectMapper mapper = new ObjectMapper();
//json String to Object
CupsProperties properties = mapper.readValue(VCAP_Services, CupsProperties.class);
System.out.println(properties.getJdbcUrl() + "!!!!!!!!!!!!!!!!!!!");
POJOS
public class UserProviderWrapper {
#JsonProperty("user-provided")
public List<CupsProperties> cupsProperties;
#JsonProperty("syslog_drain_url")
public String syslog_drain_url;
#JsonProperty("volume_mounts")
public List<String> volume_mounts;
#JsonProperty("label")
public String label;
#JsonProperty("name")
public String name;
#JsonProperty("tags")
public List<String> tags;
//getters and setters
public class CupsProperties {
#JsonProperty("jdbcUrl")
public String jdbcUrl;
#JsonProperty("spring.datasource.driver-class-name")
public String driver;
#JsonProperty("spring.datasource.initialize")
public String initialize;
//getters and setters
Error
Unrecognized field "user-provided" (class rest.springframework.model.CupsProperties), not marked as ignorable (2 known properties: "jdbcUrl", "dataSource"])
at [Source: {"user-provided":[{ "credentials": { "jdbcUrl": "jdbc:oracle:thin:user/pass//host:port/service", "spring.datasource.driver-class-name": "oracle.jdbc.OracleDriver", "spring.datasource.initialize": "false" }, "syslog_drain_url": "", "volume_mounts": [ ], "label": "user-provided", "name": "Oracle", "tags": [ ] }]}; line: 1, column: 19] (through reference chain: rest.springframework.model.CupsProperties["user-provided"])
Check below solution and see if it fulfills your need. You can build on to it if you need to parse more fields.
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonParser {
public static void main(String[] args) {
String VCAP_Services = "{\"userProvided\": [{\"credentials\": {\"accessTokenUri\": \"tokenurl\",\"apiUrl\": \"apiurl\",\"clientId\": \"typeofID\",\"clientSecret\": \"secretAf\",\"scope\": \"none\"},\"syslog_drain_url\": \"\",\"volume_mounts\": [],\"label\": \"user-provided\",\"name\": \"OAuth2\",\"tags\": []},{\"credentials\": {\"jdbcUrl\": \"jdbc:oracle:connection[host]:[port]/service\",\"spring.datasource.driver-class-name\": \"oracle.jdbc.OracleDriver\",\"spring.datasource.initialize\": \"false\"},\"syslog_drain_url\": \"\",\"volume_mounts\": [],\"label\": \"user-provided\",\"name\": \"Database\",\"tags\": [] } ] } ";
CupsProperties properties=null;
try {
JSONParser jsonParser = new JSONParser();
JSONObject vcapServiceJSONObject = (JSONObject) jsonParser.parse(VCAP_Services);
for(Object key: vcapServiceJSONObject.keySet()){
String keyStr = (String) key;
JSONArray userProvidedList = (JSONArray) vcapServiceJSONObject.get(keyStr);
Iterator i = userProvidedList.iterator();
while (i.hasNext()) {
JSONObject innerObj = (JSONObject) i.next();
JSONObject credentialsObject = (JSONObject) innerObj.get("credentials");
if(credentialsObject.containsKey("jdbcUrl")){
//set to your pojo objects
System.out.println("JDBC url:" + credentialsObject.get("jdbcUrl"));
}
if(credentialsObject.containsKey("accessTokenUri")){
//set to your pojo objects
System.out.println("Access token URI:" + credentialsObject.get("accessTokenUri"));
}
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output
Access token URI:tokenurl
JDBC url:jdbc:oracle:connection[host]:[port]/service

Parse JSON object recursively - Java

I have a JSON with list of Objects and any of the item in the list can have null or the same object as a value for a key. I am looking for a faster way to parse the json to arrive at my final result.
The data structure looks like -
[
{
"firstName": "Bruce",
"familyMembers": null
},
{
"firstName": "Gates Family",
"familyMembers": [
{
"firstName": "Bill",
"familyMembers": null
},
{
"firstName": "Steve",
"familyMembers": null
}
]
},
{
"firstName": "Lee",
"familyMembers": null
},
{
"firstName": "Chan",
"familyMembers": null
}
]
The output should be a set = ("Bruce", "Bill", "Steve", "Lee", "Chan").
I am looking for a best possible way to do this in Java, such that i dont increase my response time by getting caught in this parsing hell.
Appreciate your time on this.
Try my recursive implementation.
public static void jsonArrayToSet(JSONArray jAry, Set<String> result, String targetKey, String subArrayKey, boolean includeNode){
try {
for (int i = 0; i < jAry.length(); i++) {
JSONObject jObj = jAry.getJSONObject(i);
boolean hasSubArray = false;
JSONArray subArray = null;
if(jObj.has(subArrayKey)){
Object possibleSubArray = jObj.get(subArrayKey);
if(possibleSubArray instanceof JSONArray){
hasSubArray = true;
subArray = (JSONArray) possibleSubArray;
}
}
if(hasSubArray){
if(includeNode){
result.add(jObj.getString(targetKey));
}
jsonArrayToSet(subArray, result, targetKey, subArrayKey, includeNode);
} else {
result.add(jObj.getString(targetKey));
}
}
} catch (JSONException e){
e.printStackTrace();
}
}
jAry: The source JSONArray.
result: The Set you want to write in.
targetKey: The key that maps to an entry which you want to add to result.
subArrayKey: The key that map to a sub-JSONArray.
includeNode: When current JSONOnject is a node containing sub-array, add it to result or not.
In your case, you can call:
jsonArrayToSet(yourJsonArray, yourSet, "firstName", "familyMembers", false);
As mentioned in my comment.
Your first issue would be the content in your JSON file. Based on the standard, it should be wrapped around with a set of { }.
Example
{
"members": [
{
"firstName": "Bruce",
"familyMembers": null
},
{
"firstName": "Gates Family",
"familyMembers": [
{
"firstName": "Bill",
"familyMembers": null
},
{
"firstName": "Steve",
"familyMembers": null
}
]
},
{
"firstName": "Lee",
"familyMembers": null
},
{
"firstName": "Chan",
"familyMembers": null
}
]
}
Also, I think the value "Gates Family" should be part of the output? Since it is under the "FirstName" attribute.
Anyway, here is my solution that is based on the org.json library. It also uses Goggle's GSon library where I use it for reading the JSON file.
import org.json.*;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
public class solution {
public static final String JSON_DATA_FILE_PATH = "./data/source_37848106.json";
private static boolean hasMoreFamilyName(JSONObject json) {
return json.has("familyMembers") && json.get("familyMembers") != JSONObject.NULL;
}
private static void trackFirstName(Map<String, Integer> nameTracker, JSONObject json) {
if (!nameTracker.containsKey(json.getString("firstName"))) {
nameTracker.put(json.getString("firstName"), /*DUMMY VALUE =*/1);
}
}
private static void getNames(Map<String,Integer> nameTracker, JSONArray jsonArr) {
for (int i = 0; i< jsonArr.length(); i++) {
JSONObject item = jsonArr.getJSONObject(i);
if (hasMoreFamilyName(item)) {
getNames(nameTracker, item.getJSONArray("familyMembers"));
}
trackFirstName(nameTracker, item);
}
}
public static void main(String[] args) {
Map<String, Integer> nameTracker = new HashMap<>();
try {
String text = Files.toString(new File(JSON_DATA_FILE_PATH), Charsets.UTF_8);
JSONObject json = new JSONObject(text);
getNames(nameTracker, json.getJSONArray("members"));
}
catch (Exception ex) {
System.out.println("Something is wrong.");
}
for (Map.Entry<String,Integer> entry : nameTracker.entrySet()) {
System.out.println(entry.getKey());
}
}
You can use ObjectMapper defined in jackson-databind-2.6.5.jar
Define a java class with fields similar to json pattern and then just bind them like:
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
Family family=objectMapper.readValue(jsonString, Family.class);
Now you will have a java object similar to your json string pattern and you can print it the way you like.

Flatten JSON into Specific Format

I'd like to use Java to take in a JSON body, iterate through the records, and output every other record into a new JSON array. Each set of two records will be its own array, and I only need to take the first one in each respective array. I'll also be providing the column names in the original request that need to be added to the subsequent flattened object. For example, let's say I have the following JSON request body:
{
"records": [
[
[
"0DFC29E2-700E-4CC1-931E-B61DF4954B6B",
"John Doe",
"Teacher",
"China"
],
[
"B5B9186E-CE65-4911-8516-C510D3CC3ACE",
"Jane Doe",
"Doctor",
"London"
]
],
[
[
"20C4DD07-4E96-47F8-A1E1-B20B4C48120C",
"Jim Doe",
"Lawyer",
"Canada"
],
[
"76718CB1-238F-418E-BD14-5E2867FF3FB4",
"Jack Doe",
"Chef",
"Mexico"
]
]
],
"columns": [
"ID",
"Name",
"Occupation",
"Location"
]
}
I'd then like this request body flattened to the following:
[{
"ID": "0DFC29E2-700E-4CC1-931E-B61DF4954B6B",
"Name": "John Doe",
"Occupation": "Teacher",
"Location": "China"
},
{
"ID": "20C4DD07-4E96-47F8-A1E1-B20B4C48120C",
"Name": "Jim Doe",
"Occupation": "Lawyer",
"Location": "Canada"
}]
I'd like this code to be pretty dynamic, so it doesn't explicitly reference the column names in code. That way I can pass up other column names in the future if I have a different JSON body structure, and it will work accordingly. I'll always be passing up the data with a title of "records" so that's okay to hardcode. Any help is greatly appreciated.
You should convert source JSON into collection of maps. Each map will be contain property names and property values. After that, you can easily serialize it to expected format. In below example I use Jackson library, but I think you should be able to use Gson library too.
At first, we should define SourceEntity class which define all properties for input JSON.
class SourceEntity {
private String[][][] records;
private String[] columns;
public String[][][] getRecords() {
return records;
}
public void setRecords(String[][][] records) {
this.records = records;
}
public String[] getColumns() {
return columns;
}
public void setColumns(String[] columns) {
this.columns = columns;
}
}
After that, we should write converter, which can parse input JSON, convert arrays into collection of maps and serialize it to target JSON.
class JsonConverter {
private ObjectMapper objectMapper = new ObjectMapper();
private JsonFactory jsonFactory = new JsonFactory();
public String convert(File sourceJsonFile) throws Exception {
SourceEntity sourceEntity = parseSourceEntity(sourceJsonFile);
List<Map<String, String>> result = convertToTargetPropertiesMap(sourceEntity);
return objectMapper.writeValueAsString(result);
}
private SourceEntity parseSourceEntity(File sourceJsonFile)
throws Exception {
JsonParser parser = jsonFactory.createJsonParser(sourceJsonFile);
return objectMapper.readValue(parser, SourceEntity.class);
}
private List<Map<String, String>> convertToTargetPropertiesMap(
SourceEntity entity) {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
for (String[][] pairs : entity.getRecords()) {
list.add(createPropertyMap(entity.getColumns(), pairs[0]));
}
return list;
}
private Map<String, String> createPropertyMap(String[] names,
String[] values) {
Map<String, String> propertyMap = new LinkedHashMap<String, String>();
for (int i = 0; i < values.length; i++) {
propertyMap.put(names[i], values[i]);
}
return propertyMap;
}
}
Finally, we should write a little test:
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonProgram {
public static void main(String[] args) throws Exception {
JsonConverter converter = new JsonConverter();
String result = converter.convert(new File("/tmp/source.json"));
System.out.println(result);
}
}
Above program prints this JSON for your example input:
[{"ID":"0DFC29E2-700E-4CC1-931E-B61DF4954B6B","Name":"John Doe","Occupation":"Teacher","Location":"China"},{"ID":"20C4DD07-4E96-47F8-A1E1-B20B4C48120C","Name":"Jim Doe","Occupation":"Lawyer","Location":"Canada"}]
You can read the source JSON into a bunch of Java objects, do the transform on the Java side, and output in the new format.
It would be nice if there were a JSON equivalent to XSLT, but I haven't seen one that's in general use.

Java representation of JSON Object

I am trying to deserialize the following string, I am somewhat new to java and I cannot get this to work for the life of me... I am only trying to decode two strings in the object for now. My JSON and Java classes below. I am getting the result variable ok.
{
"result": "true",
"recentlyMarkedTerritories": {
"0": {
"pk_activity": "471",
"fk_activity_type": "100",
"activity_content": "Hhhhh",
"fk_user": "2",
"activity_image": "2_QZe73f4t8s3R1317230457.jpg",
"created": "1317244857",
"activity_status": "1",
"activity_location_lat": "43.515283",
"activity_location_lon": "-79.880678",
"fk_walk": null,
"fk_event_location": "73",
"user_point": "0",
"public_image": "0",
"fk_event_location_lat": "43.515273",
"fk_event_location_lon": "-79.879989",
"profile_image": "2_y9JlkI3CZDml1312492743.jpg",
"user_gender": "1",
"user_dob": "236073600",
"user_nickname": "junoman",
"isFriend": "false",
"profile_image_thumb": "2_y9JlkI3CZDml1312492743_t.jpg",
"activity_image_thumb": "2_QZe73f4t8s3R1317230457_t.jpg",
"relationship_status_idx": "2",
"isBlocked": "false"
},
"1": {
"pk_activity": "469",
"fk_activity_type": "100",
"activity_content": "Jsjsjs",
"fk_user": "1",
"activity_image": null,
"created": "1317244508",
"activity_status": "1",
"activity_location_lat": "43.515283",
"activity_location_lon": "-79.880678",
"fk_walk": null,
"fk_event_location": "73",
"user_point": "0",
"public_image": "0",
"fk_event_location_lat": "43.515273",
"fk_event_location_lon": "-79.879989",
"profile_image": "1_4Cpkofueqnrb1316895161.jpg",
"user_gender": "1",
"user_dob": "116841600",
"user_nickname": "JoePennington",
"isFriend": "false",
"profile_image_thumb": "1_4Cpkofueqnrb1316895161_t.jpg",
"activity_image_thumb": null,
"relationship_status_idx": "1",
"isBlocked": "false"
},
.....
}
}
And my java class below
RecentActivity infoList = null;
Gson gson = new Gson();
infoList = gson.fromJson(JSONString, RecentActivity.class);
public class RecentActivity {
String result;
recentlyMarkedTerritories recentlyMarkedTerritories = null;
public RecentActivity() {
}
public class recentlyMarkedTerritories {
public Set<recentlyMarkedTerritories> pk_activity = new HashSet<recentlyMarkedTerritories>() ;
public recentlyMarkedTerritories() { }
}
}
Please forgive my lack of description but I'm sure the code helps. The JSON is already used in other applications so changing it is not an option.. :(
Thanks!
Here are some nice Tutorials for JSON that will help you out.
GSON
JSON
JSON Example with source code
UPDATED
Try like this,
try {
JSONObject object = new JSONObject(jsonString);
JSONObject myObject = object.getJSONObject("recentlyMarkedTerritories");
for (int i = 0; i < object.length(); i++) {
JSONObject myObject2 = myObject.getJSONObject(Integer.toString(i));
System.out.println(myObject2.toString(2));
}
} catch (Exception e) {
e.printStackTrace();
}
I am not sure of the gson code to write, but the structure of your json looks more like the following java representation (though you might want booleans and ints instead of String fields):
public class RecentActivity {
String result;
Map<String,RecentlyMarkedTerritory> recentlyMarkedTerritories = null;
}
public class RecentlyMarkedTerritory {
String pk_activity;
// other fields
}

Categories