How to get a string out of (libgdx) json - java

I really wonder how this would be done properly(*):
FileHandle file = Gdx.files.local("test.json");
Json json = new Json(JsonWriter.OutputType.json);
JsonWriter writer = new JsonWriter(new StringWriter());
json.setWriter(writer);
json.writeObjectStart();
json.writeValue("name", "Testing");
json.writeObjectEnd();
file.writeString(..., false); // Here I am stuck
As you can see I want to manually (!) create a json object and write just one string in there. I do not want to use a serializer or anything the like for this matter.
In https://github.com/libgdx/libgdx/wiki/Reading-&-writing-JSON there is a passage: Serialization Methods
In there the same is done. But how can I translate my Json to a String that can be written to a file? toString() is doing no good here.
(*) Once again, I want to emphasize I do NOT want to use a serializer in that case but build my own json-file from scratch. I'm totally aware of the problems and unmanagable-code this could lead to. Thank you!

Related

Pretty print for JSON in Java works fine for the console, but in browser it does not work

I have a JSON file and I want to retrieve its content from a API call within a rest controller created in Java Spring Boot.
I get the content of the .json file into a String and use the below method ( one of them ) in order to pretty print.
If I system.out.println() the output, it gets pretty printed, but in the browser it is displayed roughly and with no indentation. I had more approaches :
String content = new String(Files.readAllBytes(resource.toPath()));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(content);
String prettyJsonString = gson.toJson(je);
System.out.println(prettyJsonString);
return prettyJsonString;
The other approach returns the same ugly output in browser, but it also adds "/r/n":
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String prettyJsonString = mapper.writeValueAsString(content);
return prettyJsonString;
Can anyone help me get the pretty output in browser as well?
Formatting String for console output and for HTML output are two VERY different tasks. Method setPrettyPrinting() is for console printing. HTML browser will ignore "\n" symbols and will not respect multiple spaces replacing them with a single space etc. In general, it is usually a client-side task to format the output. But I delt once with this problem and wrote a method that takes a console-formatted string and converts it to Html formatted String. For instance, it replaces all "\n" symbols with br Html tags. It does some other things as well. I had some success with it, but sometimes some unexpected problems occurred. You are welcome to use it. The method is available in MgntUtils Open source library. Here is its JavaDoc. The library itself is available as Maven artifact here and on Github (including source code and JavaDoc) here. An article about the library is here. Your code would look like this:
String htmlString = TextUtils.formatStringToPreserveIndentationForHtml(jsonPrettyString);
I had this same problem and stumbled upon how to get it to pretty print in the browser.
In your application.properties file, add these two lines:
# Preferred JSON mapper to use for HTTP message conversion.
spring.mvc.converters.preferred-json-mapper=gson
# Whether to output serialized JSON that fits in a page for pretty printing.
spring.gson.pretty-printing=true
Reference: https://www.callicoder.com/configuring-spring-boot-to-use-gson-instead-of-jackson/
Maybe related: https://stackoverflow.com/a/62044963

Can I transform a JSON-LD to a Java object?

EDIT: I changed my mind. I would find a way to generate the Java class and load the JSON as an object of that class.
I just discovered that exists a variant of JSON called JSON-LD.
It seems to me a more structured way of defining JSON, that reminds me XML with an associated schema, like XSD.
Can I create a Java class from JSON-LD, load it at runtime and use it to convert JSON-LD to an instantiation of that class?
I read the documentation of both the implementations but I found nothing about it. Maybe I read them bad?
Doing a Google search brought me to a library that will decode the JSON-LD into an "undefined" Object.
// Open a valid json(-ld) input file
InputStream inputStream = new FileInputStream("input.json");
// Read the file into an Object (The type of this object will be a List, Map, String, Boolean,
// Number or null depending on the root object in the file).
Object jsonObject = JsonUtils.fromInputStream(inputStream);
// Create a context JSON map containing prefixes and definitions
Map context = new HashMap();
// Customise context...
// Create an instance of JsonLdOptions with the standard JSON-LD options
JsonLdOptions options = new JsonLdOptions();
// Customise options...
// Call whichever JSONLD function you want! (e.g. compact)
Object compact = JsonLdProcessor.compact(jsonObject, context, options);
// Print out the result (or don't, it's your call!)
System.out.println(JsonUtils.toPrettyString(compact));
https://github.com/jsonld-java/jsonld-java
Apparently, it can take it from just a string as well, as if reading it from a file or some other source. How you access the contents of the object, I can't tell. The documentation seems to be moderately decent, though.
It seems to be an active project, as the last commit was only 4 days ago and has 30 contributors. The license is BSD 3-Clause, if that makes any difference to you.
I'm not in any way associate with this project. I'm not an author nor have I made any pull requests. It's just something I found.
Good luck and I hope this helped!
see this page: JSON-LD Module for Jackson

How to convert an java serialized file to json file

I have a java class already serialized and stored as .ser format file but i want to get this converted in json file (.json format) , this is because serialization seems to be inefficient in terms of appending in direct manner, and further cause corruption of file due streamcorruption errors. Is there a possible efficient way to convert this java serialized file to json format.
You can read the .ser file as an InputStream and map the object received with key/value using Gson and write to .json file
InputStream ins = new ObjectInputStream(new FileInputStream("c:\\student.ser"));
Student student = (Student) ins.readObject();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(student );
try {
//write converted json data to a file named "file.json"
FileWriter writer = new FileWriter("c:\\file.json");
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
There is no standard way to do it in Java and also there is no silver bullet - there are a lot of libraries for this. I prefer jackson https://github.com/FasterXML/jackson
ObjectMapper mapper = new ObjectMapper();
// object == ??? read from *.ser
String s = mapper.writeValueAsString(object);
You can see the list of libraries for JSON serialization/deserialization (for java and not only for java) here http://json.org/
this is because serialization seems to be inefficient in terms of appending in direct manner
Not sure if JSON is the answer for you. Could you share with us some examples of data and what manipulations you do with it?
You can try Google Protocol Buffers as alternative to Java serialization and JSON.
In my answer in topic bellow there is an overview of what GPB is and how to use, so you may check that and see if it suits you:
How to write/read binary files that represent objects?

Editing a .json file: adding lines in certain parts of the file?

I am trying to edit a ".json" file using code or scripts to attach to an installer.
I need it to add in a few lines into a .json config file but I have not found any code or online tutorials on how to do this.
I tried searching for ways to add lines to a normal .txt file but no luck on that either.
What I have found online is appending, but that's not what I need.
Maybe a way to search for certain point of the file to move the pointer to then add in the lines?
I know a little Java but no other coding language.
Is there a way to do it in Java or some small scripts?
Yes, there is a way. Here is some pseudo-code to give you the concept.
JSONObject json = fileRead("myfile.json")
JSONObject objToAdd = new JSONObject();
json.add(objToAdd);
fileWrite(json);
If you use Java 7 and your Json is not huge, this is a easy way to add lines:
List<String> lines = Files.readAllLines(Paths.get("C:\\Automation1\\some.json"), StandardCharsets.UTF_8);
lines.add(6, "{ \"abc\": 123}"); // as example add data to row 6
Files.write(Paths.get("C:\\Automation1\\some.json"), lines, StandardCharsets.UTF_8);
But this technique is hard to maintain.
I suggest you to convert Json to Object, and convert it back to Json file after you adit the Object
Use a json parser library such as json-simple. First read the content, pass it to the parser and create a Json Object. Here is an example:
JSONObject obj=new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
obj.put("nickname",null);
StringWriter out = new StringWriter();
obj.writeJSONString(out); // your writer object, i.e., FileWriter
String jsonText = out.toString();
System.out.print(jsonText);
Well you can also add one JsonObject to another: jsonObj1.add(jsonObj);

Convert Java Object into a XML String using jaxb

I would like to convert a Java Object to a String containing the marshaled XML data. One of the ways I could find was to first marshal to a File and then read the file using BufferedReader to convert into a String. I feel this may not be the most efficient way, because the IO operations are performed twice (Once during marshaling and the second time during the conversion of file content into String)
Could anyone please suggest any better approach?
Pass a StringWriter object as argument to marshal method of Marshaller
Here is the simple code by abacus-common
Account account = N.fill(Account.class);
String xml = N.toXML(account);
N.println(xml); // <account><id>6264304841028291043</id><gui>33acdcbe-fd5b-49</gui><emailAddress>19c1400a-97ae-43</emailAddress><firstName>67922557-8bb4-47</firstName><middleName>7ef242c9-8ddf-48</middleName><lastName>1ec6c731-a3fd-42</lastName><birthDate>1480444055841</birthDate><status>1444930636</status><lastUpdateTime>1480444055841</lastUpdateTime><createTime>1480444055841</createTime></account>
Account account2 = N.fromXML(Account.class, xml);
assertEquals(account, account2);
Declaration: I'm the developer of abacus-common.

Categories