write json string in JAVA - java

I am using json developing android sdk.
I found writing json string is annoying, take a look:
post_my_server("{\"cmd\":\"new_comment\"}");
I need to manually escape quotes, is there any clean way to do this?

You can use single quotes "{'cmd':'new_comment'}".
Alternatively, there is free code at http://json.org/java/ for implementing JSON at an object level. It's free as in very permissive, I am no lawyer, but it would seem that the only stipulation is that the software you include it in is good, and not evil.

To create json string use jackson core jars. The code snippet to generate a sample json string ,
JsonFactory jFactory = new JsonFactory();
StringWriter writer = new StringWriter();
/*** write to string ***/
JsonGenerator jsonGenerator = jFactory.createJsonGenerator(writer);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("company", [Value]);
jsonGenerator.writeNumberField("salary", [value]);
jsonGenerator.writeEndObject();
jsonGenerator.close();
String jsonString = writer.toString();

I use the jackson json parsers and serializers , they are completely self contained, and allow for reading, writing of any java object to and from json.
Assume you have a file called "user.json" which contains a big json in it....
private static void convert(){
Map<String,Object> userData = mapper.readValue(new File("user.json"), Map.class);
}

Related

How to extract JSON fields from an api

I have an api which returns data in the below format when i use the clientbuilder get():
final Response response = ClientBuilder.newClient().target("url").queryParam("CustomerQuery", jsonarr).request(MediaType.APPLICATION_JSON).get();
String actual = response.readEntity(String.class);
System.out.println(actual);
Result:
{"_id":{"timestamp":1649320244,"date":"2022-04-07T08:30:44.000+00:00"},"ScheduleTime":"2022-04-07T09:50:00.000+00:00","History":[{"Status":"Pending","Time":"2022-04-07T08:30:44.011+00:00"}],"MyDetails":{"Query":"query1^^","name":"NEH","address":"XXX","Format":"xml","Version":"2"}}
{"_id":{"timestamp":1649320255,"date":"2022-04-07T08:30:55.000+00:00"},"ScheduleTime":"2022-04-07T09:50:00.000+00:00","History":[{"Status":"Pending","Time":"2022-04-07T08:30:55.011+00:00"}],"MyDetails":{"Query":"query2^^^","name":"ABC","address":"YYY","Format":"xml","Version":"1"}}
I need to extract fields under MyDetails in the above string and i tried using :
final Response response = ClientBuilder.newClient().target("url").request(MediaType.APPLICATION_JSON).get();
JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
System.out.println(jsonReader.readObject());
Please let me know how can i extract the fields.
If you have questions about how to use a JsonObject, read the Javadoc https://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
JsonObject o = jsonReader.readObject();
JsonObject details = o.getJsonObject("MyDetails");
// details.get...
Alternatively, use a different http client like Retrofit that encourages direct object mapping
There are many ways to do what you want to do. I will just describe some of them. You can use several Json parsing libraries. The most popular ones are Json-Jackson also known as faster XML (See link here). You can use method readValue of ObjectMapper class. For class parameter you can use Map.class or your custom written class that will reflect the structure of your Json.
Than there is Gson library, with its user guide
But also if you want a simplistic solution, I wrote my own open-source library that includes JsonUtils class that is a thin wrapper over Json-Jackson library that gives you a very simple solution. In your case it may look like this (assuming variable json is a String that contains your Json string):
try {
Map<String, Object>map = JsonUtils.readObjectFromJsonString(json, Map.class);
Map details = map.get("MyDetails");
} catch(IOException ioe) {
...
}
Map details will contain a map with all your keys and values from section "MyDetails". If you want to use this library here is where to get it: Its called MgntUtils and you can get it on Github with Javadoc and source code. It is available as maven artifacts as well. Here is a Javadoc for JsonUtils class

Reading YAML in Java without boiler plate

I was wondering if there is a way to read a YAML file in Java without having to create a lot of POJO's but still have the ability to cleanly read the elements of the YAML. Meaning, not messing with LinkedHashmaps.
Is there a library or something that can do this?
Thanks in advance
Regards
You can use Jackson library, the ObjectMapper (the most important class of that library) has a method readTree which returns a JsonNode, which you can read and traverse. Usage is pretty simple:
String yamlString =
"---\n" +
"name: Bob\n" +
"age: 35";
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
JsonNode root = mapper.readTree(yamlString);
String name = root.get("name").asText();
int age = root.get("age").asInt();
Make sure you check some tutorials and don't get confused if you find too much stuff about JSON, because Jackson has been originally a library parsing JSON, other formats were added later.

LDIF Parser in Java (LDIF->JSON)

Do you know any java library (or sth other maybe script?) that allows you to 'convert' LDIF to JSON?
JSON data is easier for me to process, So an easy way to make such conversion would be really useful. Also I don't want to reinvent the wheel:)
Cheers
This seems to be what you are after.
You should be able to do something like:
StringWriter writer = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(writer);
FileReader reader = new FileReader("entry.ldif");
LdifReader ldifReader = new LdifReader(reader);
SearchResponse result = ldifReader.read();
jsonWriter.write(result);
System.out.println(writer.toString());
Here is a PHP script I found on github as well that does from ldif to JSON or XML.
I don't know the quality of it.

Java - JSONObject charset

I'm using JSONObject from org.json.*
I need to construct JSONObject with string fields like this
field:"englishletters123\u1234\u3456"//UTF-8 encoding
so, I'm doing this
myJSONObject.put("field", myString);
But instead of this I'm getting object with fluent (non-english) letters instead of their UTF-8 representation.
String newString = new String(oldString.getBytes(...), ...);
myJSONObject.put("field", newString);
doesn't work as well
Is there any way to make such operation? Maybe I should use some other library?
I'm not overly familiar with that JSON serialization library, but since you asked, the GSON library from google is amazing. It handles nearly everything through reflection, it's as simple as creating an object that fit the description of the JSON text you are attempting to create.
for example:
public class Thing{
public String field = "whatever you want";
}
Gson gson = new Gson();
String jsonString = gson.toJson(new Thing());
de-serializing is simple too:
Thing t = gson.fromJson(jsonString, Thing.class);
Of course, there's much more to the library, but that's the basics of it.

Formatting JSON before writing to File

Currently I'm using the Jackson JSON Processor to write preference data and whatnot to files mainly because I want advanced users to be able to modify/backup this data. Jackson is awesome for this because its incredibly easy to use and, apparently performs decently (see here), however the only problem I seem to be having with it is when I run myObjectMapper.writeValue(myFile, myJsonObjectNode) it writes all of the data in the ObjectNode to one line. What I would like to do is to format the JSON into a more user friendly format.
For example, if I pass a simple json tree to it, it will write the following:
{"testArray":[1,2,3,{"testObject":true}], "anotherObject":{"A":"b","C":"d"}, "string1":"i'm a string", "int1": 5092348315}
I would want it to show up in the file as:
{
"testArray": [
1,
2,
3,
{
"testObject": true
}
],
"anotherObject": {
"A": "b",
"C": "d"
},
"string1": "i'm a string",
"int1": 5092348315
}
Is anyone aware of a way I could do this with Jackson, or do I have to get the String of JSON from Jackson and use another third party lib to format it?
Thanks in advance!
try creating Object Writer like this
ObjectWriter writer = mapper.defaultPrettyPrintingWriter();
You need to configure the mapper beforehand as follows:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
mapper.writeValue(myFile, myJsonObjectNode);
As per above mentioned comments this worked for me very well,
Object json = mapper.readValue(content, Object.class);
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
Where content is your JSON string response
Jackson version:2.12
To enable standard indentation in Jackson 2.0.2 and above use the following:
ObjectMapper myObjectMapper = new ObjectMapper();
myObjectMapper.enable(SerializationFeature.INDENT_OUTPUT);
myObjectMapper.writeValue(myFile, myJsonObjectNode)
source:https://github.com/FasterXML/jackson-databind

Categories

Resources