Been googling a while but haven't found anything useful since keywords are too common.
Currently in my Java code method toString()
(called on some JSONObject
object) produces output like this:
{"key_name":<numerical_value>}
while what I need (due to the fact that parser on the other side of the project is imperfect) is:
{"key_name": <numerical_value>}
The only difference is that extra space after colon. Is there any JSONObject
builtin way to do it or do I need some handwritten simple string operation for it?
I can only imagine building a custom JSONStringer
. In fact, it could be a JSONWriter
built using a StringWriter
. Then you override all the value
methods to add a space before calling parent class method.
class JSONSpaceStringer extends JSONWriter {
private StringWriter sw;
JSONSpaceStringer(StringWriter sw) {
parent(sw); // initialize parent
this.sw = sw;
}
@Override
public JSONWriter value(long l) throws JSONException {
sw.write(" "); // add an initial space
parent.value(l); // and let parent class do the job...
}
// same for all other value methods
//...
}
use the below code. it will help you to solve the problem.
package com.javamad.utils;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class JsonUtils {
private static Logger logger = Logger.getLogger(JsonUtils.class.getName());
public static <T> T jsonToJavaObject(String jsonRequest, Class<T> valueType)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.UNWRAP_ROOT_VALUE,false);
T finalJavaRequest = objectMapper.readValue(jsonRequest, valueType);
return finalJavaRequest;
}
public static String javaToJson(Object o) {
String jsonString = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.UNWRAP_ROOT_VALUE,true);
jsonString = objectMapper.writeValueAsString(o);
} catch (JsonGenerationException e) {
logger.error(e);
} catch (JsonMappingException e) {
logger.error(e);
} catch (IOException e) {
logger.error(e);
}
return jsonString;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With