Convert Java data in json [duplicate] - java

This question already has answers here:
Java JSON serialization - best practice
(3 answers)
Closed 9 years ago.
I have a list of user objects in a Collection, but I want to convert this into JSON format so that on my html page I can read that json data by using javascript.
List<UserWithEmbeddedContact> users=(List<UserWithEmbeddedContact>) q.execute();
if(!users.isEmpty()) {
for(UserWithEmbeddedContact user:users) {
System.out.println("username="+user.getUsername()+
" password="+user.getPassword()+" mobile="+user.getMobile());
}
}

GSON is your answer:
From their wiki:
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
Ex:
List<UserWithEmbeddedContact> users = (List<UserWithEmbeddedContact>) q.execute();
final Type listType = new TypeToken<List<UserWithEmbeddedContact>>(){}.getType();
final String json = new Gson().toJson(users, listType);

Use json-lib for Java. It's very easy.

try this, it will convert java instance variables into JSON
import com.google.gson.Gson;
public class ObjectToJSON {
// declaring variables to be converted into JSON
private int data1 = 100;
private String data2 = "hello";
private String[] details = { "IBM", "pune", "ind", "12345" };
public static void main(String[] args) {
// Creating the class object
ObjectToJSON obj = new ObjectToJSON();
// Creating Gson class object
Gson gson = new Gson();
// convert java object to JSON format and receiving the JSON String
String json = gson.toJson(obj);
System.out.println(json);
}
}

Related

Android: gson.toJson converter giving empty string for Android objects

I'm trying to covert Java object to json using Gson library, but its not working as expected and returning empty string,
my code:
String ie = new String("Jack");
Gson gson = new Gson();
String intentcalue = gson.toJson(ie);
it returns:
{}
Please let me know if anything wrong with library, I tried with other Objects as well all returning null value like for Intent Object, ApplicationInfo etc
If you want convert string to json object, your string must be json as well.
For example:
String ie = new String("{\"name\": \"Jack\"}");
Gson gson = new Gson();
String intentcalue = gson.toJson(ie);

Converting Java String to List of maps [duplicate]

This question already has answers here:
Converting JSON data to Java object
(14 answers)
Closed 8 years ago.
I get a json string in server side as follow
[ {"projectFileId":"8547",
"projectId":"8235",
"fileName":"1",
"application":"Excel",
"complexity":"NORMAL",
"pageCount":"2",
"targetLanguages":" ar-SA",
"Id":"8547"
},
{"projectFileId":"8450",
"projectId":"8235",
"fileName":"Capacity Calculator.pptx",
"application":"Powerpoint",
"complexity":"NORMAL",
"pageCount":"100",
"targetLanguages":" ar-LB, ar-SA",
"Id":"8450"
}
]
I want to convert this string into an arraylist or map whichever possible so that I can iterate over it and get the field values.
You can use GSON library. Simply use Gson#fromJson() method to convert JSON string into Java Object.
sample code:
BufferedReader reader = new BufferedReader(new FileReader(new File("json.txt")));
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Map<String, String>>>() {}.getType();
ArrayList<Map<String, String>> data = gson.fromJson(reader, type);
// convert back to JSON string from object
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
You can create a POJO class to convert it directly into List of POJO clas object to access it easily.
sample code:
class PojectDetail{
private String projectFileId;
private String projectId;
private String fileName;
private String application;
private String complexity;
private String pageCount;
private String targetLanguages;
private String Id;
// getter & setter
}
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<PojectDetail>>() {}.getType();
ArrayList<PojectDetail> data = gson.fromJson(reader, type);

How to save and load game in javafx

I'm programming an easy version of blackjack without bets in javafx, and I'm almost done with every part but now I want to be able to save and load my BlackJack game but i have no idea how to do it. Can I save everything as txt file and then load it or is there any easy way of doing it? my game layout
Consider a json serializer/deserializer like Google GSON.
Define json structure according to your data model and just serialize and deserialize your game objects to/from json file.
Example:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
// Serialization
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
// ==> json is {"value1":1,"value2":"abc"}
// Deserialization
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
// ==> obj2 is just like obj
You can write to a file using FileOutputStream and read from a file using FileInputStream. I would use json format and have Jackson do all serialization but that's just me.

Convert json string to list or map [duplicate]

This question already has answers here:
Converting JSON data to Java object
(14 answers)
Closed 8 years ago.
I get a json string in server side as follow
[ {"projectFileId":"8547",
"projectId":"8235",
"fileName":"1",
"application":"Excel",
"complexity":"NORMAL",
"pageCount":"2",
"targetLanguages":" ar-SA",
"Id":"8547"
},
{"projectFileId":"8450",
"projectId":"8235",
"fileName":"Capacity Calculator.pptx",
"application":"Powerpoint",
"complexity":"NORMAL",
"pageCount":"100",
"targetLanguages":" ar-LB, ar-SA",
"Id":"8450"
}
]
I want to convert this string into an arraylist or map whichever possible so that I can iterate over it and get the field values.
You can use GSON library. Simply use Gson#fromJson() method to convert JSON string into Java Object.
sample code:
BufferedReader reader = new BufferedReader(new FileReader(new File("json.txt")));
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Map<String, String>>>() {}.getType();
ArrayList<Map<String, String>> data = gson.fromJson(reader, type);
// convert back to JSON string from object
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
You can create a POJO class to convert it directly into List of POJO clas object to access it easily.
sample code:
class PojectDetail{
private String projectFileId;
private String projectId;
private String fileName;
private String application;
private String complexity;
private String pageCount;
private String targetLanguages;
private String Id;
// getter & setter
}
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<PojectDetail>>() {}.getType();
ArrayList<PojectDetail> data = gson.fromJson(reader, type);

Java convert ArrayList to string and back to ArrayList?

I wanted to save an ArrayList to SharedPreferences so I need to turn it into a string and back, this is what I am doing:
// Save to shared preferences
SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("myAppsArr", myAppsArr.toString());
editor.commit();
I can retrieve it with String arrayString = sharedPref.getString("yourKey", null); but I don't know how to convert arrayString back into an ArrayList. How can it be done?
My array looks something like:
[item1,item2,item3]
You have 2 choices :
Manually parse the string and recreate the arraylist. This would be pretty tedious.
Use a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,
// How to store JSON string
Gson gson = new Gson();
// This can be any object. Does not have to be an arraylist.
String json = gson.toJson(myAppsArr);
// How to retrieve your Java object back from the string
Gson gson = new Gson();
DataObject obj = gson.fromJson(arrayString, ArrayList.class);
Try this
ArrayList<String> array = Arrays.asList(arrayString.split(","))
This will work if comma is used as separator and none of the items have it.
The page http://mjiayou.com/2015/07/22/exception-gson-internal-cannot-be-cast-to/ contains the following:
Type type = new TypeToken<List<T>>(){}.getType();
List<T> list = gson.fromJson(jsonString, type)
perhaps it will be helpful.
//arraylist convert into String using Gson
Gson gson = new Gson();
String data = gson.toJson(myArrayList);
Log.e(TAG, "json:" + gson);
//String to ArrayList
Gson gson = new Gson();
arrayList=gson.fromJson(data, new TypeToken<List<Friends>>()
{}.getType());
I ended up using:
ArrayList<String> appList = new ArrayList<String>(Arrays.asList(appsString.split("\\s*,\\s*")));
This doesn't work for all array types though. This option differs from:
ArrayList<String> array = Arrays.asList(arrayString.split(","));
on that the second option creates an inmutable array.
Update to Dhruv Gairola's answer for Kotlin
val gson = Gson();
val jsonString = gson.toJson(arrayList)

Categories