JSONObject shows escape characters - java

I have a manual json object that i created and I use escape characters for one of the fields. I see escape strings whenever i print my jsonobject, is there a way to remove them? I'm just worried that the client will get the json object with the escaped strings when i send this over through the server.
String car_parameters = "{\"property_name\":\"car_id\",\"traceKey\":\"account_id,accountName,car_id\"}";
System.out.println("car params"+car_parameters);
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", car_parameters);
System.out.println("one"+jsonObject);
System.out.println("two"+payload);
These are the outputs respectively, i tried converting json object to string but that did not make a difference.I'd expect to see json object's fields without escape characters like when i print out just the string.
car params{"property_name":"car_id","traceKey":"account_id,accountName,car_id"}
one{"message":"{\"property_name\":\"car_id\",\"traceKey\":\"account_id,accountName,car_id\"}"}
two{"message":"{\"property_name\":\"car_id\",\"traceKey\":\"account_id,accountName,car_id\"}"}

The escape character is caused by Java syntax. Java does not allow
String car_parameters = "{"property_name":"car_id","traceKey":"account_id,accountName,car_id"}"
is converted automatically.
You can turn it into an object, as shown below
System.out.println("toString"+JSONObject.parse(car_parameters));
output:
Object:{"traceKey":"account_id,accountName,car_id","property_name":"car_id"}
in addition:
If you send it to the client, it will also be {"message": "{property_ name":"car_ id","traceKey":"account_ id,accountName,car_ id"}"}
\It will become a part of the string, so the front end needs to handle it, but the transfer in Java does not affect the use.

You can do this. please consider what artifact you need.(My favorite is ObjectMapper.)
If you need generate from string, it is simple.
Maybe there is a lot of harsh way but I think it is not necessary now.
Remember that A first sample need new artifact as below in your pom.xml
<!-- for the JSONParser -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
public void JSonTest() throws JSONException, ParseException {
String car_parameters = "{\"property_name\":\"car_id\",\"traceKey\":\"account_id,accountName,car_id\"}";
System.out.println("car params"+car_parameters);
JSONParser jsonParser = new JSONParser();
Object myObject = jsonParser.parse(car_parameters);
System.out.println("One" + myObject);
// Put it separate.
JSONObject jsonObject = new JSONObject();
jsonObject.put("property_name", "car_id");
jsonObject.put("traceKey", "account_id,accountName,car_id");
System.out.println("Two"+jsonObject);
jsonObject.remove("property_name");
jsonObject.remove("traceKey");
// Put it a map first.
HashMap<String, String> myMap = new HashMap<>();
myMap.put("property_name", "car_id");
myMap.put("traceKey", "account_id,accountName,car_id");
jsonObject.put("message", myMap);
System.out.println("Three"+jsonObject);
}
And Here is output,
car params{"property_name":"car_id","traceKey":"account_id,accountName,car_id"}
One{"traceKey":"account_id,accountName,car_id","property_name":"car_id"}
Two{"traceKey":"account_id,accountName,car_id","property_name":"car_id"}
Three{"message":"{traceKey=account_id,accountName,car_id, property_name=car_id}"}

Related

Java Reading From JSON

I am looking to get the weather from this weather API I am using in a Netbeans Java project into my own Maven API, this is all working fine but returning a huge chunky JSON response when I want to break it down into smaller readable text.
My code is currently returning:
{"coord":{"lon":-6.26,"lat":53.35},"weather":[{"id":801,"main":"Clouds","description":"few
clouds","icon":"02d"}],"base":"stations","main":{"temp":285.59,"pressure":1015,"humidity":58,"temp_min":285.15,"temp_max":286.15},"visibility":10000,"wind":{"speed":3.6,"deg":80},"clouds":{"all":20},"dt":1539610200,"sys":{"type":1,"id":5237,"message":0.0027,"country":"IE","sunrise":1539586357,"sunset":1539624469},"id":2964574,"name":"Dublin","cod":200}
I would instead like it to be able to return, main in weather and temp in weather as well. If anyone has any ideas let me know. Code is attached.
public class WeatherInfo {
public static String getWeather(String city) {
String weather;
String getUrl = "http://api.openweathermap.org/data/2.5/weather?q="+ city +"&appid=xxx";
Client client = Client.create();
WebResource target = client.resource(getUrl);
ClientResponse response = target.get(ClientResponse.class);
weather = response.getEntity(String.class);
return weather;
}
}
I am assuming your desired return value from getWeather is {"main":"Clouds","temp":285.59}
Here is a solution for that -
add jackson dependency in your pom
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
And here is a method that strips out other details and returns only main and temp, you can edit this method to add more fields.
private static String getLessWeather(String weatherJson) throws IOException {
Map<String, Object> lessWeatherMap = new LinkedHashMap<String, Object>();
Map<String,Object> weatherMap = new ObjectMapper().readValue(weatherJson, LinkedHashMap.class);
String main = (String) ((LinkedHashMap)((ArrayList)weatherMap.get("weather")).get(0)).get("main");
lessWeatherMap.put("main", main);
Double temp = (Double)((LinkedHashMap)weatherMap.get("main")).get("temp");
lessWeatherMap.put("temp", temp);
return new ObjectMapper().writeValueAsString(lessWeatherMap);
}
You need to use a library to parse the JSON response. Here is an SO question with great examples and references: How to parse JSON in Java
The answer from user SDekov lists three good options:
Google GSON
Org.JSON
Jackson

Converting malformed json array string to Java object

I have a malformed json array string which I get from an API call as follows:
[{\"ResponseCode\":1,\"ResponseMsg\":\"[{\"Code\":\"CA2305181\",\"Message\":\"Processed successfully\"}]\"}]
There is a double quote before open square bracket in the value of Response Msg property.
Is there a way to convert this into Java object ?
What I have tried so far:
I have used Jackson to parse it as follows but it gives error
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new ResponseNameStrategy());
Response[] response = mapper.readValue(strOutput1, Response[].class);
Error: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token
I have also tried using Gson to parse it but it also gives error
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
Response[] response = gson.fromJson(strOutput1, Response[].class);
Error: Expected BEGIN_ARRAY but was STRING at line 1 column 35 path $[0].ResponseMsg
I have gone through the following links on StackOverflow but none of them has addressed my issue:
How to Convert String Array JSON in a Java Object
Convert a JSON string to object in Java ME?
JSON Array to Java objects
Convert json String to array of Objects
converting 'malformed' java json object to javascript
I think the answer is in the comments, you appear to be trying to solve the issue on the wrong place.
You are receiving json which you wish to parse into java objects, unfortunately the json is malformed so will not parse.
As a general rule you should never be trying to solve the symptom, but should look for the root cause and fix that, it may sound trivial but fixing symptoms leads to messy, unpredictable, and unmaintainable systems.
So the answer is fix the json where it is being broken. If this is something or of your control, while you wait for the fix, you could put a hack in to fix the json before you parse it.
This way you won't compromise your parsing, and only have a small piece of string replacement to remove when the third party has fixed the issue. But do not go live with the hack, it should only be used during development.
As i mentioned in the comment, you should prepare your service response in order to parse it.
I implemented an example:
public class JsonTest {
public static void main(String args[]) throws JsonProcessingException, IOException{
String rawJson =
"[{\"ResponseCode\":1,\"ResponseMsg\":\"[{\"Code\":\"CA2305181\",\"Message\":\"Processed successfully\"}]\"}]";
String goodJson = "{"+rawJson.split("[{{.}]")[2]+"}";
ObjectMapper mapper = new ObjectMapper();
final ObjectNode node = mapper.readValue(goodJson, ObjectNode.class);
System.out.println("Pretty Print: " + mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node));
System.out.println("Just code: " + node.get("Code"));
}
}
Which returns:
This is how I finally solved my issue:
String inputJsonStr = "[{\"ResponseCode\":1,\"ResponseMsg\":\"[{\"Code\":\"CA2305181\",\"Message\":\"Claim has been added successfully.\"}"
+ "]\"}]";
int indexOfRes = inputJsonStr.indexOf("ResponseMsg");
if(inputJsonStr.substring(indexOfRes+13,indexOfRes+14).equals("\""))
{
inputJsonStr = inputJsonStr.substring(0,indexOfRes+13) + inputJsonStr.substring(indexOfRes+14);
}
int indexOfFirstClosingSquare = inputJsonStr.indexOf("]");
if(inputJsonStr.substring(indexOfFirstClosingSquare+1, indexOfFirstClosingSquare+2).equals("\"")) {
inputJsonStr = inputJsonStr.substring(0, indexOfFirstClosingSquare+1)+inputJsonStr.substring(indexOfFirstClosingSquare+2);
}
Now inputJsonStr contains a valid json array which can be parsed into Java custom object array easily with gson as given in this SO link:
Convert json String to array of Objects

String deserialization and conversion to JSON in Java

After deserializing my string and converting it to JSON using the code below:
JSONObject returnValue = new JSONObject();
String toJson = null;
try
{
Object otherObjectValue = SerializationUtils
.deserialize(myBytesArray);
Gson gson = new Gson();
toJson = gson.toJson(otherObjectValue);
returnValue.put(key, toJson);
}
some part of the JSON still has something like:
{ "key":"ATTRIBUTE_LIST", "value":"{\"attributeContract\":[{\"scope\":\"sso\",\"name\":\"SAML_SUBJECT\",\"description\":\"Click to Edit\",\"required\":true}]}"}
which means everything in:
"{\"attributeContract\":[{\"scope\":\"sso\",\"name\":\"SAML_SUBJECT\",\"description\":\"Click to Edit\",\"required\":true}]}"
is one string instead being another object with fields. Is there something I can do to sanitize by JSONObject to make it properly JSON?
The key part is OK, means the whole String is JSON formatted.
For the value part, /shows that the value of value is JSON formatted already.
So you may "deserialize" the value of value again to retrieve an Object result. Or you may ask the creator of origin JSON, to serialize origin Object one time into JSON format.

how to manipulate HTTP json response data in Java

HttpGet getRequest=new HttpGet("/rest/auth/1/session/");
getRequest.setHeaders(headers);
httpResponse = httpclient.execute(target,getRequest);
entity = httpResponse.getEntity();
System.out.println(EntityUtils.toString(entity));
Output as follows in json format
----------------------------------------
{"session":{"name":"JSESSIONID","value":"5F736EF0A08ACFD7020E482B89910589"},"loginInfo":{"loginCount":50,"previousLoginTime":"2014-11-29T14:54:10.424+0530"}}
----------------------------------------
What I want to know is how to you can manipulate this data using Java without writing it to a file?
I want to print name, value in my code
Jackson library is preferred but any would do.
thanks in advance
You may use this JSON library to parse your json string into JSONObject and read value from that object as show below :
JSONObject json = new JSONObject(EntityUtils.toString(entity));
JSONObject sessionObj = json.getJSONObject("session");
System.out.println(sessionObj.getString("name"));
You need to read upto that object from where you want to read value. Here you want the value of name parameter which is inside that session object, so you first get the value of session as JSONObject using getJSONObject(KeyString) and read name value from that object using function getString(KeyString) as show above.
May this will help you.
Here's two ways to do it without a library.
NEW (better) Answer:
findInLine might work even better. (scannerName.findInLine(pattern);)
Maybe something like:
s.findInLine("{"session":{"name":"(\\w+)","value":"(\\w+)"},"loginInfo":{"loginCount":(\\d+),"previousLoginTime":"(\\w+)"}}");
w matches word characters (letters, digits, and underscore), d matches digits, and the + makes it match more than once (so it doesnt stop after just one character).
Read about patterns here https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
OLD Answer:
I'm pretty sure you could use a scanner with a custom delimiter here.
Scanner s = new Scanner(input).useDelimiter("\"");
Should return something like:
{
session
:{
name
:
JSESSIONID
,
value
:
5F736EF0A08ACFD7020E482B89910589
And so on. Then just sort through that list/use a smarter delimiter/remove the unnecessary bits.
Getting rid of every other item is a pretty decent start.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html has info on this.
I higly recomend http-request built on apache http api.
private static final HttpRequest<Map<String, Map<String, String>>> HTTP_REQUEST = HttpRequestBuilder.createGet(yourUri, new TypeReference<Map<String, Map<String, String>>>{})
.addDefaultHeaders(headers)
.build();
public void send(){
ResponseHandler<Map<String, Map<String, String>>> responseHandler = HTTP_REQUEST.execute();
Map<String, Map<String, String>> data = responseHandler.get();
}
If you want use jackson you can:
entity = httpResponse.getEntity();
ObjectMapper mapper = new ObjectMapper();
Map<String, Map<String, String>> data = mapper.readValue(entity.getContent(), new TypeReference<Map<String, Map<String, String>>>{});

Using Json with java returns string with \" instead of "

Am using jsonobject and json array and converting the final result to string using jsonobject.toString() function and returning the string to browser.
Code snippet:
JSONArray VMs= new JSONArray();
JSONObject resultSet = new JSONObject();
for(Vector<String> stages : mrs)
{
VMs.put(new JSONObject().put("Vm",stages.get(0)));
}
resultSet.append("ServerDetails",(new JSONObject().put("Server",sName).append("Vms", stageNames)));
return resultSet.toString();
output on browser:
"{\"ServerDetails\":[{\"Server\":\"myserver45\",\"Vms\":[[{\"Vm\":\"vm1022\"},{\"Vm\":\"vm9875\"}]]}]}"
I don't want it to return this way. How do i make this return as follows without slashes-
"{"ServerDetails":[{"Server":"myserver45","Vms":[[{"Vm":"vm1022"},{"Vm":"vm9875"}]]}]}"
I don't understand why " gets replaced with \" everywhere. Please help.
If you are using net.sf.json json library, both jsonObject and jsonObject.toString() provide output values without string escape character. Which library you are using..?
Also try returning the original jsonObject itself than the one converted with toString. It might give you the desired result.
Alternate option would be to unescape the string which is send to browser. You can use stringescapeutils from org.apache.commons.lang for this return StringEscapeUtils.unescapeJava(resultSet.toString()) ;

Categories