withDefaultPrettyPrinter() doesn't make the output be formatted - java

I want to save some json to file
This is my serializtion code:
private String serializeToJson(T item) {
String json;
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
try {
json = ow.writeValueAsString(item);
} catch (IOException e) {
e.printStackTrace();
json = "";
}
return json;
}
and yet my json is save to file not formatted:
e.g. part of it is:
{"path":{"segmentId":69798169,"nodeId":18477384,"x":-71.12074,"y":42.33235},"street":1,"altStreets":null,"distance":59,"length":178,"crossTime":49,"crossTimeWithoutRealTime":49,"tiles":[0,1],"clientIds":[166,177],"instruction":

Tried Jackson pretty print mapper?assumed object has implemented toString method
ObjectMapper mapper = new ObjectMapper();
  try {
    System.out.println("Default output:"+mapper.writeValueAsString(object));
  System.out.println("Pretty printing:\n"+mapper.defaultPrettyPrintingWriter().writeValueAsString(object));    
 

Related

Check if JSON fits the needed class using GSON

I have a class like
data class Data(
val field1: Int = 123
val field2: String = "Foo"
)
I have JSON like
{"field1": 123, "field2": "Foo"}
How can I check if my JSON really represents the structure of the class using Google GSON?
Hi bro there are several Ways first by using code
import org.json.*;
public boolean isValidJSONTest(String yourjsonString) {
try {
new JSONObject(yourjsonString);
} catch (JSONException ex) {
try {
new JSONArray(yourjsonString);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
For Gson code is like
Gson gson = new Gson();
try {
Object o = gson.fromJson(json, Object.class);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(o));
} catch (Exception e) {
System.out.println("invalid json format");
}
second you can use browser console and paste your string in console and enter
third they are several website that can validate json format or view etc
https://jsonlint.com/

How to parsing JSON like this?

I have json data format like
{
"status":200,
"message":"ok",
"response": {"result":1, "time": 0.0123, "values":[1,1,0,0,0,0,0,0,0]
}
}
I want to get one value of values array and put it on textView in eclipse. Look my code in eclipse
protected void onPostExecute (String result){
try {
JSONobject json = new JSONObject(result);
tv.setText(json.toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}
You can use GSON
Create a POJO for your response
public class Response{
private int result;
private double time;
private ArrayList<Integer> values;
// create SET's and GET's
}
And then use GSON to create the object you desire.
protected void onPostExecute (String result){
try {
Gson gson = new GsonBuilder().create();
Response p = gson.fromJson(result, Response.class);
tv.setText(p.getValues());
}catch (JSONException e){
e.printStackTrace();
}
}
You can use jackson library for json parsing.
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readTree(json);
map.get("key");
You can use readTree if you know json is an instance of JSONObject class else use typeref and go with readValue to get the map.
protected void onPostExecute (String result){
try {
JSONObject json = new JSONObject(result);
JSONObject resp = json.getJSONObject("response");
JSONArray jarr = resp.getJSONArray("values");
tv.setText(jarr.get(0).toString(1));
}catch (JSONException e){
e.printStackTrace();
}
}

Convert JsonObject to Json String with Jackson

I am using Jackson and am able to get a JSONObject. I need to be able to convert this JSONObject to its json form. Meaning, the object that is represented by this JSONObject's son string.
Something like:
JsonObject object = ...;
object.toJsonString();
A simple Google search surprisingly didn't turn up many response and I am unable to see how to do it on my own.
Any ideas?
Try,
JSONObject object = ...;
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(object);
StringWriter out = new StringWriter();
object.writeJSONString(out);
String jsonText = out.toString();
System.out.print(jsonText);
If you need to bridge the 2 APIs you can create a custom StdSerializer.
More on custom serializers:
https://www.baeldung.com/jackson-custom-serialization
private static class JSONObjectSerializer extends StdSerializer<JSONObject> {
JSONObjectSerializer(){
this(null);
}
JSONObjectSerializer(Class<JSONObject> t) {
super(t);
}
#Override public void serialize(JSONObject value, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeStartObject();
value.keys().forEachRemaining(key-> {
try {
gen.writeStringField(key,value.getString(key));
} catch (IOException ex){
throw new RuntimeException("Encountered an error serializing the JSONObject.",ex);
}
});
gen.writeEndObject();
}
private static SimpleModule toModule(){
return new SimpleModule().addSerializer(JSONObject.class, new JSONObjectSerializer());
}
}
//.......
ObjectWriter writer = new ObjectMapper()
.registerModule(JSONObjectSerializer.toModule())
.writerWithDefaultPrettyPrinter();
//.......
try {
s = w.writeValueAsString(v);// v being your JSONObject or parent
} catch (JsonProcessingException ex) {
throw new RuntimeException("Unable to write object to json.", ex);
}

can I set json to be pretty print only in some attributes?

I have a json with many attributes.
I want some of them to be inline. Meaning with no new break lines.
Here is my code today:
private String serializeToJson(T item) {
String json;
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
try {
json = ow.writeValueAsString(item);
} catch (IOException e) {
e.printStackTrace();
json = "";
}
return json;
}
how can I set it to be not "pretty print" for attribute path like this { "path" : { "segmentId" : 31788674, "nodeId" : 26161441, "x" : -74.236605 ...
I serialized this specific property to inline json string separately.
public ResultUiShort(ResultLong result) {
this.path = stringUtils.toInlineJson(result.path);
...
}
and
public <T> String toInlineJson(T item) {
String json;
ObjectWriter ow = new ObjectMapper().writer();
try {
json = ow.writeValueAsString(item);
} catch (IOException e) {
e.printStackTrace();
json = "";
}
return json;
}

Jackson serialize multiple objects into one

I've got an Ajax call to populate multiple fields in the front end from Hibernate Objects. That's why I would like to return multiple Java Hibernate to Json serialized objects to Ajax from Spring. Currently I do:
#RequestMapping(method=RequestMethod.GET)
#ResponseBody
public String getJson()
{
List<TableObject> result = serviceTableObject.getTableObject(pk);
String json = "";
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
try
{
json = ow.writeValueAsString(result);
} catch (JsonGenerationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
This works fine and returns a json object to ajax but I have multiple objects like that so what I want is to nest all these objects in one json object and return the latter to my ajax so I can populate all fields using one object rather than making multiple ajax calls for each object I need. So for example I would to have something like:
List<TableObject> result = serviceTableObject.getTableObject(pk);
String json = "";
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
json = ow.writeValueAsString(result);
List<SecondObject> secondObject = serviceSecondObject.getSecondObject(pk);
String json2 = "";
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
json2 = ow.writeValueAsString(secondObject );
NewJsonObject.add(json)
NewJsonObject.add(json2)
return newJsonObject;
You should be able to just use a Map (since JSON Objects aren't anything different than a Map) to hold your objects:
#RequestMapping(method=RequestMethod.GET)
#ResponseBody
public String getJson() {
Map<String, Object> theMap = new LinkedHashMap<>();
// if you don't care about order just use a regular HashMap
// put your objects in the Map with their names as keys
theMap.put("someObject", someModelObject);
// write the map using your code
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
return ow.writeValueAsString(theMap);
}
You can now access all the objects in the Map in your JS, since the Map will get serialized as a JSON-Object:
response.someObject == { // JSON Serialization of someModelObject }

Categories