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.
Related
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);
I am creating a program whereby I need to save(write) objects to a JSON, and then load(read) these objects back into the program. I have told that GSON is a good way to do this. However, I am having some troubles with it. I have tried the following:
Gson g = new Gson();
try (FileWriter writer = new FileWriter(file)) {
String j = g.toJson(board);
writer.write(j);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
When I run the program, I get the error:
class object3 declares multiple JSON fields named state
The object I am trying to write to the JSON has an ID, and an Array of another Object (object2), and each of these objects have an Array of another Object (object3). object3 has multiple fields, mostly strings. What is the simplest way for me to write an object such as this to a JSON file and then be able to read it back into my program?
If you simply want to serialize and deserialize object state in a JSON format, and don't care too much about the exact shape of the JSON, XStream makes this very easy. It tolerates almost any Java object structure and isn't as pernickety as Gson.
It was originally designed to serialize to XML, but if you use the JettisonMappedXmlDriver it will output JSON instead. I have found it to be a well-written and reliable library.
Product product = new Product("Banana", "123", 23.00);
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("product", Product.class);
System.out.println(xstream.toXML(product));
Produces:
{"product":{"name":"Banana","id":123,"price":23.0}}
To read it back in:
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias("product", Product.class);
Product product = (Product) xstream.fromXML(json);
System.out.println(product.getName());
Prints:
Banana
I am reading a JSON file into one string and one array. I already have a string where the JSON is saved, let's call it myString. Here is the JSON file:
As you can see, the file contains three styles, from "styleCount": "3". My goal is to now create three string variables for each style, similar to the following pseudo variables:
String name_style1 should contain: "Sommer-Fashion"
String name_style2 should contain: "Dream-Style"
String name_style3 should contain: "Perfect-Look"
Then I need an array of strings for each style with the SKU numbers:
private String[] sku_style1 = new String[6];
sku_style1[0] = "392714";
sku_style1[1] = "395895";
sku_style1[2] = "392450";
sku_style1[3] = "371706";
sku_style1[4] = "383748";
sku_style1[5] = "385275";
And also for the other styles:
private String[] sku_style2 = new String[6];
private String[] sku_style3 = new String[6];
Is there a function of Java which helps with simply adding elements from a JSON file (or in my case a string: myString) into a string and an array?
Any help is appreciated.
Google GSON! No functions native to Java really help much, but Google GSON has helped me numerous times with issues much harder than this. I think you'll find it very helpful. Here is a link!
https://mvnrepository.com/artifact/com.google.code.gson/gson
EDIT
This link is for the repository for the jar downloads!
EDIT 2
Gson gson = new Gson();
Staff obj = new Staff();
// 1. Java object to JSON, and save into a file
gson.toJson(obj, new FileWriter("D:\\file.json"));
// 2. Java object to JSON, and assign to a String
String jsonInString = gson.toJson(obj);
There are JSON parson libraries that serve this exact purpose.
JSONArray
JSONString
Read more here.
I am putting some java objects in the Json at server side
like this :
ArrayList<VisjsNode>visjsNodes = new ArrayList<VisjsNode>();
ArrayList<VisjsConnection> visjsConnections = new ArrayList<VisjsConnection>();
String jsondata = null;
org.json.JSONObject object = new org.json.JSONObject();
try {
object.put("nodes", visjsNodes);
object.put("connections", visjsConnections);
jsondata = object.toString();
Now is there a way I can get these objects back from this json (jsondata) at client side
I am doing this:
com.google.gwt.json.client.JSONValue jsonValue = JSONParser.parseStrict(jsondata);
com.google.gwt.json.client.JSONObject jsonObject = jsonValue.isObject();
jsonValue = jsonObject.get("nodes");
Now I am trying this to get ArrayList back , by doing this
ArrayList<VisjsNode>visjsNodesFromjson = jsonValue ;
But its not compiling ,it says Incompatable types...
Can you please guide how we can retrieve the Java Object back from Json ..
That's because you're using two different JsonObject class. First you use the one which comes from org.json (org.json.JsonObject) and the other is com.google.gwt.json.client.JSONObject. Nevertheless, they're named similar, they're completely different classes.
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);
}
}