Put variable into json text body - java

is that any idea on putting variable into json text body and POST it out? Here is my text body
final String POST_PARAMS = "{\n" + "\"company\": 101,\r\n" +
" \"product\": 101,\r\n" +
" \"condition\": \"Test Title\",\r\n" +
" \"delivery_time\": \"Test Body\``"" + "\n}";

You have to use org.json.JSONObject
Example:
myString = new JSONObject()
.put("JSON", "Hello, World!").toString();
produces the string {"JSON": "Hello, World"}

Related

Ignore a key in JSON to XML conversion

I am using json library to convert json to xml but while converting I want to ignore a nested json object to be converted to xml tags.
eg.
Plane json is as :
{"id":"9568","name":"Customer Analysis","group":"demo","param":{"globalSettings":{"showLegends":false,"legendPosition":"bottom center"}}}
JSONObject json = new JSONObject("{\"id\":\"9568\",\"name\":\"Customer Analysis\",\"group\":\"demo\",\"param\":{\"globalSettings\":{\"showLegends\":false,\"legendPosition\":\"bottom center\"}}}");
String xml = XML.toString(json);
System.out.println(xml);
Now in above example, I want in xml with a json as it is inside. Whereas now various elements are created for showLegends and legendPosition inside globalSettings.
Current XML is as follows :
<name>Customer Analysis</name>
<id>9568</id>
<group>demo</group>
<param>
<globalSettings>
<showLegends>false</showLegends>
<legendPosition>bottom center</legendPosition>
</globalSettings>
</param>
Expected XML should be as follows :
<name>Customer Analysis</name>
<id>9568</id>
<group>demo</group>
<param>
<globalSettings>
{"showLegends":false,"legendPosition":"bottom center"}
</globalSettings>
</param>
How can I handle this?
I think you need to tweak JSON before converting.
Can you try this below?
String json = "{\n" +
" \"user\": \"gerry\",\n" +
" \"likes\": [1, 2, 4],\n" +
" \"followers\": {\n" +
" \"options\": {\n" +
" \"key1\": \"a\",\n" +
" \"key2\": \"b\"\n" +
" } \n" +
" }\n" +
"}";
JSONObject jsonObject = new JSONObject(json);
JSONObject followers = jsonObject.getJSONObject("followers");
String options = followers.optString("options");
followers.put("options", options);
String s = XML.toString(jsonObject);
System.out.println(XML.unescape(s));
result:
<followers><options>{"key1":"a","key2":"b"}</options></followers><user>gerry</user><likes>[1,2,4]</likes>
Extra Question:
What if I don't want options as an xml element and it should be part of json?
String json = "{\n" +
" \"user\": \"gerry\",\n" +
" \"likes\": [1, 2, 4],\n" +
" \"followers\": {\n" +
" \"options\": {\n" +
" \"key1\": \"a\",\n" +
" \"key2\": \"b\"\n" +
" } \n" +
" }\n" +
"}";
JSONObject jsonObject = new JSONObject(json);
jsonObject.put("followers", jsonObject.optString("followers"));
// org.json 20180813
String s = XML.toString(jsonObject);
System.out.println(XML.unescape(s));
result:
<followers>{"options":{"key1":"a","key2":"b"}}</followers><user>gerry</user><likes>1</likes><likes>2</likes><likes>4</likes>
You need to modify your json a bit:
String json = "{\"user\":\"gerry\",\"likes\":[1,2,4],\"followers\":{\"options\":\"{key1:a,key2:b}\"}}";
JSONObject jsonObject = new JSONObject(json);
String xml = XML.toString(jsonObject);
System.out.println(XML.unescape(xml));
note that the "options" should be as "String" (shaped like JSON), then the XML parser will treat it as a regular string.
You either need to tweak the JSON before conversion, or tweak the XML after conversion.
Since such tweaking is so often required, one approach is to do the conversion using XSLT 3.0 so you have transformation capability built-in to the tool.
Underscore-java library has static methods U.fromJson(json) and U.toXml(map). You may modify map and generate xml. I am the maintainer of the project.
Map<String, Object> map = U.fromJsonMap("{\"id\":\"9568\",\"name\":\"Customer Analysis\",\"group\":\"demo\",\"param\":{\"globalSettings\":{\"showLegends\":false,\"legendPosition\":\"bottom center\"}}}");
U.set(map, "param.globalSettings", U.toJson((Map<String, Object>) U.get(map, "param.globalSettings")));
System.out.println(U.toXml(map));
Output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<id>9568</id>
<name>Customer Analysis</name>
<group>demo</group>
<param>
<globalSettings>{
"showLegends": false,
"legendPosition": "bottom center"
}</globalSettings>
</param>
</root>

What is the java library to remove/modify a json object based on json path, or how to fix the below issue in JsonPath?

I am trying to implement a function to be able to remove or modify a json object base on a specified json path. For example, if i have a below json string/object:
{
"PersonalDetailsDTO": {
"FirstName": "Mark",
"LastName": "Sully",
"TotalDependent": "2",
"DOB": "19811212",
"SecQuestion": "Some Que",
"SecAnswer": "Some-Ans",
"Mobile": "0123456789",
"Email": "some#validemail.com",
"Title": "Mr",
"EmploymentListDTO": [
{
"Type": "Full-time",
"Probation": true
}
],
"AddressListDTO": [
{
"AddressType": "BUS",
"PostCode": "1234",
"State": "NSW",
"StreetName": "miller",
"StreetNumber": "111",
"StreetType": "Invalid",
"Suburb": "Sydney",
"UnitNumber": "Maximum"
}
]
}
}
And i want to remove element $.PersonalDetailsDTO.AddressListDTO.PostCode.
I've done quite some search, and the one lib i found is JsonPath: http://static.javadoc.io/com.jayway.jsonpath/json-path/2.2.0/com/jayway/jsonpath/JsonPath.html
So i wrote the below code:
public static void main(String[] args) {
// Prints "Hello, World" to the terminal window.
String jsonString = "{\n" +
" \"PersonalDetailsDTO\": {\n" +
" \"FirstName\":\"Mark\",\n" +
" \"LastName\":\"Sully\",\n" +
" \"Title\":\"Mr\",\n" +
" \"DOB\":\"19811201\",\n" +
" \"SecQuestion\":\"Some Ques\",\n" +
" \"SecAnswer\":\"Some-Ans\",\n" +
" \"Email\":\"some#validemail.com\",\n" +
" \"EmploymentListDTO\": [\n" +
" {\n" +
" \"Type\": \"Full-time\",\n" +
" \"Probation\": true\n" +
" }\n" +
" ],\n" +
" \"AddressListDTO\": [\n" +
" {\n" +
" \"AddressType\": \"Residential\",\n" +
" \"PostCode\": \"2345\",\n" +
" \"State\": \"NSW\",\n" +
" \"StreetName\": \"MEL\",\n" +
" \"StreetNumber\": \"2\",\n" +
" \"StreetType\": \"Boulevard\",\n" +
" \"Suburb\": \"Melbourne\",\n" +
" \"UnitNumber\": \"345\"\n" +
" }\n" +
" ]\n" +
" } \n" +
"}";
JSONObject jsonObject = new JSONObject(jsonString);
System.out.println("Before: " + jsonObject.toString());
JsonPath jp = JsonPath.compile("$.PersonalDetailsDTO.AddressListDTO[0].PostCode");
Configuration conf = Configuration.defaultConfiguration();
Object json = conf.jsonProvider().parse(jsonString);
System.out.println("After: " + jp.delete(json, conf).toString());
}
And the console log displays:
Before: {"PersonalDetailsDTO":{"EmploymentListDTO":[{"Type":"Full-time","Probation":true}],"SecAnswer":"Some-Ans","Email":"some#validemail.com","SecQuestion":"Some Ques","FirstName":"Mark","DOB":"19811201","AddressListDTO":[{"StreetName":"MEL","Suburb":"Melbourne","State":"NSW","StreetNumber":"2","UnitNumber":"345","AddressType":"Residential","PostCode":"2345","StreetType":"Boulevard"}],"Title":"Mr","LastName":"Sully"}}
After: {PersonalDetailsDTO={FirstName=Mark, LastName=Sully, Title=Mr, DOB=19811201, SecQuestion=Some Ques, SecAnswer=Some-Ans, Email=some#validemail.com, EmploymentListDTO=[{"Type":"Full-time","Probation":true}], AddressListDTO=[{"AddressType":"Residential","State":"NSW","StreetName":"MEL","StreetNumber":"2","StreetType":"Boulevard","Suburb":"Melbourne","UnitNumber":"345"}]}}
Looks like JsonPath is doing it's job and removing $.PersonalDetailsDTO.AddressListDTO.PostCode. However, there's something very obvious that bothers me:
Looking at the json string produced by .toString() in before and after case, JSONObject API printed a nice string in true json standard format with every double quotes "" present, while the JsonPath .toString produce a customer string format that has some elements in double quote "" while others are not and i can not use it further like JSONObject.
And what i noticed is that although JsonPath claim to accept "java.lang.Object" as parameter in many of its function, what it truely accept is something called "jsonProvider". Not sure if it's causing the weird .toString() behavior.
Anyway, does anyone know how get a nice formatted json string out of JsonPath APIs like remove(), put(), read() and many other? Or to convert the return value to something like JSONObject?
If you know any other Java lib that can do remove/modify element by json path, please feel free to recommand. Thank you!
I don't know JsonPath.
I think you should use jackson which is defacto standard lib when work with JSON in java
aproximate what you are going to do is:
String jsonString = "{"k1": {"k2":"v2"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(jsonString);
actualObj.at("/k1/k2").getValueAsInt()
and replace getValueAsInt with any other function

Get field from json using regex

I have the following json document:
{
"videoUrl":"",
"available":"true",
"movie":{
"videoUrl":"http..."
},
"account":{
"videoUrl":"http...",
"login":"",
"password":""
}
}
In this json I have a property named videoUrl, I want to get first non empty videoUrl
My regex:
("videoUrl":)("http.+")
But this regex match the following String
"videoUrl" :"http..."},
"account" : {"videoUrl" : "http...","login" : "","password" : ""
What is my way to write Regex that will find first non empty videoUrl with it's value
(Result should be "videoUrl":"http...")
Add (?!,) at the end of the regex, it will make the regex stop at an , without capturing it:
public static void main(String[] args) {
String input = "{ \n" +
" \"videoUrl\":\"\",\n" +
" \"available\":\"true\",\n" +
" \"movie\":{ \n" +
" \"videoUrl\":\"http...\"\n" +
" },\n" +
" \"account\":{ \n" +
" \"videoUrl\":\"http...\",\n" +
" \"login\":\"\",\n" +
" \"password\":\"\"\n" +
" }\n" +
"} ";
Pattern pattern = Pattern.compile("(\"videoUrl\":)(\"http.+\")(?!,)");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group()); // "videoUrl":"http..."
}
}
It will be more appropriate to use one of JSON parsers, like Gson or Jackson, instead of regex. Something like:
String jsonStr = "...";
Gson gson = new Gson();
JsonObject json = gson.fromJson(jsonStr, JsonObject.class);
String url = element.get("videoUrl").getAsString();

How can I pass Json object to servlet response writer?

I want to pass JSON data to ajax function. But it gives me parsing exception
$(document).ready(function(){
$(".count").on('blur', function(){
var pack_count = $(this).val();
var order_id = $(this).attr('id');
$.post("order?action=update_counter&pack_count=" + pack_count + "&order_id=" + order_id, function(data){
alert("Change is successfull! Price: ");
$("#sum").html("Order Price: " + data);
var price = data['order_sum'];
var pack_count = data['pack_count'];
document.getElementById('price').value = price;
$(this).val(pack_count);
})
});
});
resp.setContentType("application/json; charset=UTF-8");
PrintWriter out = resp.getWriter();
String jsonData = "{ \"pack_count\" : \"" + selectedOrder.getPackageCount() + "\", \"order_sum\" : \"" + countSum() + "\" }";
out.print(jsonData);
Update:
Solved it! Thanks to printfmyname
and backslash comments. Just changed jsonData to
String jsonData = "{ " + "\"pack_count\" : " + selectedOrder.getPackageCount() + ", \"order_sum\" : " + countSum() + " }";
You are wring a json string to output but your header is by default set to text/html or something that is not json. So you need to set proper header before writing to output
response.setContentType("application/json; charset=UTF-8"); # you may get rid of ; charset=UTF-8 as it is not critical
Then when you done writing to output call
out.flush();
Update:
You have an error on
String jsonData = "{ \"pack_count\" : \"" + selectedOrder.getPackageCount() + ", \"order_sum\" : " + countSum() + " }";
you a missing a quotation after selectedOrder.getPackageCount() , change to follwong
String jsonData = "{ \"pack_count\" : \"" + selectedOrder.getPackageCount() + "\", \"order_sum\" : " + countSum() + " }";

How can i add double quotes to look like json

i am having below string but i want to add double quotes in it to look like json
[
{
LastName=abc,
FirstName=xyz,
EmailAddress=s#s.com,
IncludeInEmails=false
},
{
LastName=mno,
FirstName=pqr,
EmailAddress=m#m.com,
IncludeInEmails=true
}
]
i want below output.
[
{
"LastName"="abc",
"FirstName"="xyz",
"EmailAddress"="s#s.com",
"IncludeInEmails"=false
},
{
"LastName"="mno",
"FirstName"="pqr",
"EmailAddress"="m#m.com",
"IncludeInEmails"=true
}
]
i have tried some string regex. but didn't got. could any one please help.
String text= jsonString.replaceAll("[^\\{\\},]+", "\"$0\"");
System.out.println(text);
thanks
The regex way, similar to you have tried:
String jsonString = "[ \n" + "{ \n" + " LastName=abc, \n" + " FirstName=xyz, \n"
+ " EmailAddress=s#s.com, \n" + " IncludeInEmails=false \n" + "}, \n" + "{ \n"
+ " LastName=mno, \n" + " FirstName=pqr, \n" + " EmailAddress=m#m.com, \n" + " Number=123, \n"
+ " IncludeInEmails=true \n" + "} \n" + "] \n";
System.out.println("Before:\n" + jsonString);
jsonString = jsonString.replaceAll("([\\w]+)[ ]*=", "\"$1\" ="); // to quote before = value
jsonString = jsonString.replaceAll("=[ ]*([\\w#\\.]+)", "= \"$1\""); // to quote after = value, add special character as needed to the exclusion list in regex
jsonString = jsonString.replaceAll("=[ ]*\"([\\d]+)\"", "= $1"); // to un-quote decimal value
jsonString = jsonString.replaceAll("\"true\"", "true"); // to un-quote boolean
jsonString = jsonString.replaceAll("\"false\"", "false"); // to un-quote boolean
System.out.println("===============================");
System.out.println("After:\n" + jsonString);
Since there are a lot of corner cases, like character escaping, booleans, numbers, ... a simple regex won't do.
You could split the input string by newline and then handle each key-value-pair separately
for (String line : input.split("\\R")) {
// split by "=" and handle key and value
}
But again, you will have to handle char. escaping, booleans, ... (and btw, = is not a valid JSON key-value separator, only : is).
I'd suggest using GSON since it provides lenient parsing. Using Maven you can add it to your project with this dependency:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
You can then parse your input string using
String output = new JsonParser()
.parse(input)
.toString();
Just use this library http://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1
Here is code for your example:
JSONArray json = new JSONArray();
JSONObject key1 = new JSONObject();
key1.put("LastName", "abc");
key1.put("FirstName", "xyz");
key1.put("EmailAddress", "s#s.com");
key1.put("IncludeInEmails", false);
JSONObject key2 = new JSONObject();
key2.put("LastName", "mno");
key2.put("FirstName", "pqr");
key2.put("EmailAddress", "m#m.com");
key2.put("IncludeInEmails", true);
json.add(key1);
json.add(key2);
System.out.println(json.toString());
Use the below code to get the output for your expection,
public class jsonTest {
public static void main(String[] args){
String test="[{ LastName=abc, FirstName=xyz, EmailAddress=s#s.com,IncludeInEmails=false},{ LastName=mno, FirstName=pqr, EmailAddress=m#m.com, IncludeInEmails=true}]";
String reg= test.replaceAll("[^\\{\\},]+", "\"$0\"");
String value=reg.replace("\"[\"{", "[{").replace("=","\"=\"").replace(" ","").replace("}\"]\"","}]").replace("\"true\"", "true").replace("\"false\"", "false");
System.out.println("value :: "+value);
}
}

Categories

Resources