How to convert JSON to a string with escape characters - java

I am new to JMeter java and Minidev. I am working on this existing module where I have to use minidev libraries I need to convert a JSON form non-indented format to a string format in Jmeter. The API requires a String representation of the JSON due to some characters.
To give an example, I have {"Item":"Value","MyList":["A","B","C"]} which I want to convert as "{\"Item\":\"Value\",\"MyList\":[\"A\",\"B\",\"C\"]}"
I have tried using JSONObject.toString() or JSONObject.toJSONString() however this does not give me desired results. I am using Jmeter 5 with Java 12
I did not find any good solution in short time so right now I am using below code however I would love to do it the right way.
String postJSON = root.toJSONString().replace("\"","\\\"");
postJSON = postJSON.replace("{","\"{");
postJSON = postJSON.replace("}","}\"");

Related

How to url encode data in Java

So Im trying to translate a working python code into Java. One of the steps required is to url encode the data. But when I encode the data in Java it looks different than the one in encoded in Python.
In one of the block of Python code theres this:
data = {'request-json': json}
print('Sending form data:', data)
data = urlencode(data)
data = data.encode('utf-8')
print('Sending data:', data)
The Output
Sending form data: {'request-json': '{"apikey": "xewpjipcpovwiiql"}'}
The output after being encoded
Sending data: b'request-json=%7B%22apikey%22%3A+%22xewpjipcpovwiiql%22%7D'
So this is what im trying to do in Java. As you can imagine Java is more involved. I used gson to convert to Json
Gson gson = new Gson();
API_Key key = new API_Key("xewpjipcpovwiiql");
String jsonInputString = gson.toJson(key);
Data data = new Data(key);
String request_form = gson.toJson(data);
System.out.println(request_form);
String urlencoded = URLEncoder.encode(request_form,StandardCharsets.UTF_8);
System.out.println(urlencoded);
The output:
Sending form data: {"request-json":{"apikey":"xewpjipcpovwiiql"}}
The output of the encoded string:
%7B%22requestjson%22%3A%7B%22apikey%22%3A%22xewpjipcpovwiiql%22%7D%7D
So they dont look the same so why are they coming differently ? How do I get the same python encoded String in Java ? I noticed in Python it used a combination of single and double quotes and in Java its only Double quotes so I dont know if that makes a difference.
Thank You!
On the Python side: The data.encode('utf-8') call is not necessary or at least the documentation describes with a different intention compared to this use https://docs.python.org/3/library/stdtypes.html#str.encode (and that's why there's a b' at the beggining).
The outer brackets are missing because it is interpreting request-json as the URL parameter name (it may be easier to understand if you add a second property at the json's top/first property level, you'll see you end with request-json=%7B%22apikey%22%3A+%22xewpjipcpovwiiql%22%7D&second-property=<second-property-value>).
On the Java side: the request_form is being completely interpreted as a single value to encode so you can put the encoded value as part of some parameter in a URL, as in: https://host:port?some-parameter-name=%7B%22requestjson%22%3A%7B%22apikey%22%3A%22xewpjipcpovwiiql%22%7D%7D

Interpolate JSON values into a string

I am writing an application/class that will take in a template text file and a JSON value and return interpolated text back to the caller.
The format of the input template text file needs to be determined. For example: my name is ${fullName}
Example of the JSON:
{"fullName": "Elon Musk"}
Expected output:
"my name is Elon Musk"
I am looking for a widely used library/formats that can accomplish this.
What format should the template text file be?
What library would support the template text file format defined above and accept JSON values?
Its easy to build my own parser but there are many edge cases that needs to be taken care of and I do not want to reinvent the wheel.
For example, if we have a slightly complex JSON object with lists, nested values etc. then I will have to think about those as well and implement it.
I have always used org.json library. Found at http://www.json.org/.
It makes it really easy to go through JSON Objects.
For example if you want to make a new object:
JSONObject person = new JSONObject();
person.put("fullName", "Elon Musk");
person.put("phoneNumber", 3811111111);
The JSON Object would look like:
{
"fullName": "Elon Musk",
"phoneNumber": 3811111111
}
It's similar to retrieving from the Object
String name = person.getString("fullName");
You can read out the file with BufferedReader and parse it as you wish.
Hopefully I helped out. :)
This is how we do it.
Map inputMap = ["fullName": "Elon Musk"]
String finalText = StrSubstitutor.replace("my name is \${fullName}", inputMap)
You can try this:
https://github.com/alibaba/fastjson
Fastjson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Fastjson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Modify JSON database values with java in eclipse

I want to use eclipse and java to make a program that can parse json files in java only.
For example, I want to change a value in JSON to another value every second.
I know the jsonparse function in javascript, but to carry it over through scriptengine alone seems like a bad solution.
I also know that I can use Apache IO to read a file to string and then edit the string and read the file back, but it doesn't seem efficient.
Is there an effective way to modify values in a JSON.php file?
Here is a JSON.php file that I have.
[{"color": "red waves-effect waves-light", "value": "0", "activator": "null"}]
Here is a part of my java program that does the text editing.
String attentionVs = "" + attentionV;
File fileattentionV = new File("attentionV.php");
String fileContext2 = FileUtils.readFileToString(fileattentionV);
fileContext2 = attentionVs;
FileUtils.write(fileattentionV, fileContext2);
String meditationVs = "" + meditationV;
File filemeditationV = new File("meditationV.php");
fileContext2 = FileUtils.readFileToString(filemeditationV);
fileContext2 = meditationVs;
FileUtils.write(filemeditationV, fileContext2);
Thanks for your help!
Going on just the first sentence where you say you want to parse a JSON file in Java, have you seen this post How to parse JSON in Java

How would I split this string?

How would I go about cutting this giant string? I need the data of the first ID," preferably for the string output to be:
"id":1,"name":"site1","has_doneit":true,"destination":"4613"
Is this possible? Or if not any other ways of grabbing the name:"site1" and the has_doneit:true would be perfectly fine.
{"needs_complete":true,"has_done":true,"sites":[
{"id":1,"name":"site1","has_doneit":true,"destination":"4613"},{"id":2,"name":"site2","has_doneit":true,"destination":"4613"},{"id":3,"name":"site3","has_doneit":true,"destination":"4339"},{"id":4,"name":"site4","has_doneit":true,"destination":"4340"},{"id":5,"name":"site5","has_doneit":true,"destination":"4341"},
{"id":6,"name":"site6","has_doneit":true,"destination":"4622"},{"id":7,"name":"site7","has_doneit":true,"destination":"4623"},{"id":8,"name":"site8","has_doneit":true,"destination":"4828"},
{"id":9,"name":"site9","has_doneit":true,"destination":"4829"},{"id":10,"name":"site10","has_doneit":true,"destination":"4861"}]}
That seems like a JSON string so use a Json Parser...
PHP: JSON_decode
$parsedStr = json_decode($yourString, true);
you can access sites array in $parsedStr['sites']
So, to access the id of the first site:
echo $parsedStr['sites'][0]['id'];
Java
check this answer in SO Decoding JSON String in Java

ISO-8859-1 encoded strings out of /into JSON in Java

My application has a Java servlet that reads a JSONObject out of the request and constructs some Java objects that are used elsewhere. I'm running into a problem because there are strings in the JSON that are encoded in ISO-8859-1. When I extract them into Java strings, the encoding appears to get interpreted as UTF-16. I need to be able to get the correctly encoded string back at some point to put into another JSON object.
I've tried mucking around with ByteBuffers and CharBuffers, but then I don't get any characters at all. I can't change the encoding, as I have to play nicely with other applications that use ISO-8859-1.
Any tips would be greatly appreciated.
It's a legacy application using Struts 1.3.8. I'm using net.sf.json 2.2.4 for JSONObject and JSONArray.
A snippet of the parsing code is:
final JSONObject a = (JSONObject) i;
final JSONObject attr = a.getJSONObject("attribute");
final String category = attr.getString("category");
final String value = attr.getString("value");
I then create POJOs using that information, that are retrieved by another action class to create JSON to pass to the client for display, or to pass to other applications.
So to clarify, if the JSON contains the string "Juan Guzmán", the Java String contains something like Juan Guzm?_An (I don't have the exact one in front of me). I'm not sure how to get the correct diacritical back. I believe that if I can get a Java String that contains the correct representation, that Mezzie's solution, below, will allow me to create the string with the correct encoding to put back into the JSON to serve back.
I had the same issue and I am using the same technology as you are. In our case, it was UTF 8. so just change that to UTF-16
public static String UTF8toISO( String str )
{
try
{
return new String( str.getBytes( "ISO-8859-1" ), "UTF-8" );
}
catch ( UnsupportedEncodingException e )
{
e.printStackTrace();
}
return str;
}

Categories

Resources