Json String - How to add variables in the string - java

I have a Json string like below
String jsonRequestString = "{\"access_code\" : \"9bPbN3\" , "
+ "\"merchant_reference\" : \"123\", \"language\" : \"en\",\"id\" : \"149018273\","
+ "\"merchant_identifier\" : \"gKc\", \"signature\" : \"570fd712af47995468550bec2655d9e23cdb451d\", "
+ "\"command\" : \"VOID\"}";
I have a String variable as
String code = "9bPbN3";
Question, how do I plugin the above string instead of hardcoding it at the below place. i.e. instead of 9bPbN3, I want to use the variable code there.
String jsonRequestString = "{\"access_code\" : \"9bPbN3\" , "
Many Thanks in advance.

If you are struggling to arrange the "'s the correct syntax would be
String jsonRequestString = "{\"access_code\" : \""+code+"\" , ";
Instead of formatting Json string manually, which takes alot of effort, consider using a library or util.
For ex (going to use Jackson library) :
Request re = new Request();
re.setCode(code);
...
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(re);

String yourVariable = "xyz";
String jsonRequestString = "{\"access_code\" : \"" + yourVariable + "\" , "
+ "\"merchant_reference\" : \"123\", \"language\" : \"en\",\"id\" : \"149018273\","
+ "\"merchant_identifier\" : \"gKc\", \"signature\" : \"570fd712af47995468550bec2655d9e23cdb451d\", "
+ "\"command\" : \"VOID\"}";

General advice is to avoid crafting a json structure out of vanilla strings. Instead use a json parser/writer library for this operations.
Checkout http://stleary.github.io/JSON-java/index.html / http://stleary.github.io/JSON-java/index.html .
There a various other libraries and tutorials available.
If you don't want to go this direction, use a "known value" placeholder and substitute it. So the full json would contain "access_code" : "##ACCESS_CODE##" and you would Substitute the placeholder with the real value. So your json string would be some kind of a string template.

Another option would be to use the format method like so:
String jsonRequestString = "{\"access_code\" : \"%s\" , "
+ "\"merchant_reference\" : \"123\", \"language\" : \"en\",\"id\" : \"149018273\","
+ "\"merchant_identifier\" : \"gKc\", \"signature\" : \"570fd712af47995468550bec2655d9e23cdb451d\", "
+ "\"command\" : \"VOID\"}";
String code = "9bPbN3";
String result = String.format(jsonRequestString, code);
Notice the "%s" I put in the place of where code would go. When you call the format method with code as a parameter, it puts it where the "%s" was.

Related

How can I retrieve qrcode data from an object?

I have a method that can return QRcode data in {'p':1,"x":10,"y":20} this format and it is captured in a variable called qrdata (which is a String data type ).
My question is how can I retrieve value from that key , value pair object ?if .... String qrdata = readQR(image) then how can I retrieve data from qrdata ?
You can use the JSONObject class from javax.json as mentioned in BuildSlayer's answer.
In the example in your question you use simple quotes for 'p'. Assuming it is not a typo and you meant that different charcacters can be used as quotes, you could run into trouble using it though. In that case, you could use plain java to parse your qrData String:
public String[] parseJSON(String qrData){
String[] output = new String[qrData.length()];
int i = 0;
for (String keyValuePair:qrData.split(",")) {
output[i++] = keyValuePair.split(":")[1];
}
return output;
}
}
You can do the following:
JSONObject jsonObject = new JSONObject(qrData);
System.out.println("p: " + jsonObject.getInt("p"));
System.out.println("x: " + jsonObject.getInt("x"));
System.out.println("y: " + jsonObject.getInt("y"));
Output:
p: 1
x: 10
y: 20

Array type found error when try to call from an array of string urls

I just have a question in running a Get request based on string urls.
The code below determines the string urls and puts each urls in an array for a table row.
final String URL_CORE = “/test/platform/auth”;
List<String> urls = new ArrayList<>();
rows.forEach(row -> {
final String clientValue = row.getCell("client");
final String uriValue = row.getCell("uri");
final String typeValue = row.getCell("type"));
urls.add(URL_CORE + "?" +
(clientValue.isEmpty ? "" : CLIENT + "=" + clientValue + "&") +
(uriValue.isEmpty ? "" : URI + "=" + uriValue + "&") +
(typeValue.isEmpty ? "" : TYPE + "=" + typeValue);
});
Within the forEach, I have this code where I just want to run the get request for the url string (for each row at a time). It is giving me an erray type expected found and wondering what am I doing wrong?
getRequest(queryParamsList[row]);
It seems by the name that queryParamsList is a List, not an array, so you have to access element by list.get(index) method. If you dont have the index, you can get it by list.indexOf(element)

Translating json to string variable

I'm working on developping a webservice that communicate two application with each other, the first application will send a json object to the second one.
I'm stuck in translating this json object :
$body = "{"fields":{"project":{"key":"'+$projectKey+'"}
,"issuetype":{"name": "'+$issueType+'"}
,"summary":"'+$summary+'"
,"description":"'+$description+'"
,"customfield_12721":"'+$FirstName+'"
,"customfield_12722":"'+$LastName+'"
,"customfield_12723":{"value":"'+$EmployeeCategory+'"}
,"customfield_12732":"'+$Externalfunction+'"
,"customfield_12725":"'+$CorporateID+'"
,"customfield_12726":{"value":"'+$VermegCompany+'"}
,"customfield_12685":{"value":"'+$IndusRegion+'"}
,"customfield_12673":{"value":"'+$Product+'"}
,"customfield_12727":{"value":"'+$Profile+'"}
,"customfield_12667":{"name":"'+$Manager+'"}
,"customfield_12708":"'+$BeginDate+'"
,"customfield_14000":"'+$Reglementation+'"
,"customfield_14001":"'+$Department+'"
,"customfield_14002":"'+$SubDepartment+'"}
}";
To a String variable like :
String json = "{fields:{project:{\"key\":\""+ projectkey +"}"
+ "\",\"issuetype\":\""
+ "\",\"customfield_12721\":\"" + employee.getFirstName()
+ "\",\"description\":\"" + description
+ "\",\"summary\":\"" + summary
+ "\",\"customfield_12722\":\""+ employee.getLastName()
+ "\",\"customfield_12732\":\"" + employee.getFte()
+ "\",\"customfield_14000\":\"" + employee.getReglementation()
+ "\",\"customfield_14001\":\"" + employee.getDepartment()
+ "\",\"customfield_14002\":\"" + employee.getSubdepartment()
+ "\",\"fulltime\":" + Math.round(Double.parseDouble(employee.getFulltime().replaceAll(",",".")))
//+ ",\"email\":\"" + employee.getEmail()
+ ",\"citizenship\":\"" + employee.getCitizenship()
+ "\",\"gnn\":\""+ employee.getGnn()
+ "\",\"company\":\"" + employee.getCompany()
+ "\",\"employeeid\":\"" + employee.getEmployeeid()
+ "\",\"customfield_12708\":\"" + employee.getStartdate()
//+ "\",\"enddate\":\"" //+ employee.getEnddate()
+ "\",\"product\":\"" + employee.getProduct()
+ "\",\"customfield_12725\":\"" + employee.getInternalnumber()
// + "\",\"employeeid\":\"" + employee.getEmployeeid()
+ "\"}}";
Can you please help ?
Here you can use JsonConvert library to get json data.bellow are the example how to use it
String json = "{\"FirstName\":\"Jack\",\"LastName\":\"Tor\"}";
var data = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
Console.WriteLine(data);
Console.ReadLine();
Using a web tool
If you just want to convert it fast into a string, you can use a Json to String converter on the web.
Using a library
If you however want a good solution in you applications, a way to solve this problem would be to serialize and parse using a library such as GSON. This is of course, if you don't intend to create this conversion yourself.
GSON is quite easy to use and takes care of the translation for you. Se example below:
The sending application:
Gson gson = new Gson();
String jsonStr = gson.toJson(employee); // Serialize (from Java class to JSON string)
// Send data (jsonStr) ...
The receiving application:
// Receive data (jsonStr) ...
Gson gson = new Gson();
Employee employee = gson.fromJson(jsonStr); // Parse (from JSON string to Java class)
GSON will by default name the fields the same as the member variable names in the Java class. If you need to change the field names in the JSON string, you can use #SerializedName("newName") in front of the member variables.
Example:
class Employee {
...
#SerializedName("customfield_12721") String firstName;
...
}

Convert HOCON string into Java object

One of my webservice return below Java string:
[
{
id=5d93532e77490b00013d8862,
app=null,
manufacturer=pearsonEducation,
bookUid=bookIsbn,
model=2019,
firmware=[1.0],
bookName=devotional,
accountLinking=mandatory
}
]
I have the equivalent Java object for the above string. I would like to typecast or convert the above java string into Java Object.
I couldn't type-cast it since it's a String, not an object. So, I was trying to convert the Java string to JSON string then I can write that string into Java object but no luck getting invalid character "=" exception.
Can you change the web service to return JSON?
That's not possible. They are not changing their contracts. It would be super easy if they returned JSON.
The format your web-service returns has it's own name HOCON. (You can read more about it here)
You do not need your custom parser. Do not try to reinvent the wheel.
Use an existing one instead.
Add this maven dependency to your project:
<dependency>
<groupId>com.typesafe</groupId>
<artifactId>config</artifactId>
<version>1.3.0</version>
</dependency>
Then parse the response as follows:
Config config = ConfigFactory.parseString(text);
String id = config.getString("id");
Long model = config.getLong("model");
There is also an option to parse the whole string into a POJO:
MyResponsePojo response = ConfigBeanFactory.create(config, MyResponsePojo.class);
Unfortunately this parser does not allow null values. So you'll need to handle exceptions of type com.typesafe.config.ConfigException.Null.
Another option is to convert the HOCON string into JSON:
String hoconString = "...";
String jsonString = ConfigFactory.parseString(hoconString)
.root()
.render(ConfigRenderOptions.concise());
Then you can use any JSON-to-POJO mapper.
Well, this is definitely not the best answer to be given here, but it is possible, at least…
Manipulate the String in small steps like this in order to get a Map<String, String> which can be processed. See this example, it's very basic:
public static void main(String[] args) {
String data = "[\r\n"
+ " {\r\n"
+ " id=5d93532e77490b00013d8862, \r\n"
+ " app=null,\r\n"
+ " manufacturer=pearsonEducation, \r\n"
+ " bookUid=bookIsbn, \r\n"
+ " model=2019,\r\n"
+ " firmware=[1.0], \r\n"
+ " bookName=devotional, \r\n"
+ " accountLinking=mandatory\r\n"
+ " }\r\n"
+ "]";
// manipulate the String in order to have
String[] splitData = data
// no leading and trailing [ ] - cut the first and last char
.substring(1, data.length() - 1)
// no linebreaks
.replace("\n", "")
// no windows linebreaks
.replace("\r", "")
// no opening curly brackets
.replace("{", "")
// and no closing curly brackets.
.replace("}", "")
// Then split it by comma
.split(",");
// create a map to store the keys and values
Map<String, String> dataMap = new HashMap<>();
// iterate the key-value pairs connected with '='
for (String s : splitData) {
// split them by the equality symbol
String[] keyVal = s.trim().split("=");
// then take the key
String key = keyVal[0];
// and the value
String val = keyVal[1];
// and store them in the map ——> could be done directly, of course
dataMap.put(key, val);
}
// print the map content
dataMap.forEach((key, value) -> System.out.println(key + " ——> " + value));
}
Please note that I just copied your example String which may have caused the line breaks and I think it is not smart to just replace() all square brackets because the value firmware seems to include those as content.
In my opinion, we split the parse process in two step.
Format the output data to JSON.
Parse text by JSON utils.
In this demo code, i choose regex as format method, and fastjson as JSON tool. you can choose jackson or gson. Furthermore, I remove the [ ], you can put it back, then parse it into array.
import com.alibaba.fastjson.JSON;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SerializedObject {
private String id;
private String app;
static Pattern compile = Pattern.compile("([a-zA-Z0-9.]+)");
public static void main(String[] args) {
String str =
" {\n" +
" id=5d93532e77490b00013d8862, \n" +
" app=null,\n" +
" manufacturer=pearsonEducation, \n" +
" bookUid=bookIsbn, \n" +
" model=2019,\n" +
" firmware=[1.0], \n" +
" bookName=devotional, \n" +
" accountLinking=mandatory\n" +
" }\n";
String s1 = str.replaceAll("=", ":");
StringBuffer sb = new StringBuffer();
Matcher matcher = compile.matcher(s1);
while (matcher.find()) {
matcher.appendReplacement(sb, "\"" + matcher.group(1) + "\"");
}
matcher.appendTail(sb);
System.out.println(sb.toString());
SerializedObject serializedObject = JSON.parseObject(sb.toString(), SerializedObject.class);
System.out.println(serializedObject);
}
}

Can't understand why I'm getting a 'String index out of range: -3' error - Java

I have a Java program reading from a text file, and I'm trying to set a variable to the String between two strings - between "text" : " and " , "date . I keep getting the error 'String index out of range: -3', and I can't seem to find any other solutions which I can apply to my code.
String filename5 = "C:\\Users\\Steven\\Desktop\\Tests\\wunderground
\\outputTweetsWeatherAlerts.txt";
String filename6 = filename5;
FileInputStream input_file5 = new FileInputStream(filename5);
Scanner input5 = new Scanner(input_file5);
input5.findInLine("\"id\"");
String tweetText1 = input5.next();
int startPosition = tweetText1.indexOf(": \"") + ": \"".length();
System.out.println("Start Position: " + startPosition);
int endPosition = tweetText1.indexOf("\" , \"date", startPosition);
System.out.println("endPosition " + endPosition);
String tweetText = tweetText1.substring(startPosition, endPosition);
// THIS LINE CAUSES ERROR: String index out of range: -3
System.out.println(tweetText);
The text file I'm reading is as follows:
{ "_id" : { "$oid" : "507dc77633f77fd20f7eec96"} , "id" : 258307760112955393 , "text" : "Some random text" , "date" : { "$date" : ... }
Any help would be appreciated! Thanks
The following works for me (or at least doesn't throw an error) which suggests that findInLine() (which you haven't shown us) is not returning what you think it should be returning.
As Philip Whitehouse suggests in the comments, maybe your line of text is actually split over two lines?
You need to print out the results at each step to see what is going wrong, or use a debugger to examine the variables.
String tweetText1 = "{ \"_id\" : { \"$oid\" : \"507dc77633f77fd20f7eec96\"} , \"id\" : 258307760112955393 , \"text\" : \"Some random text\" , \"date\" : { \"$date\" : ... }";
int startPosition = tweetText1.indexOf(": \"") + ": \"".length();
System.out.println(startPosition);
int endPosition = tweetText1.indexOf("\" , \"date", startPosition);
System.out.println(endPosition);
String tweetText = tweetText1.substring(startPosition, endPosition);
// THIS LINE CAUSES ERROR: String index out of range: -3
System.out.println(tweetText);
This outputs:
start
22
105
507dc77633f77fd20f7eec96"} , "id" : 258307760112955393 , "text" : "Some random text
Looking at the code, you are probably using Scanner incorrectly. Try printing out tweetText1 and it'll give you an empty string. What you could probably do is to retain the FileInputStream, get the contents of the file and put into a String by using a recursive fis.read and adding the char in a StringBuilder (as an example) then use #DNA 's code.
OR the best alternative I can think of is to use input5.nextLine() instead of input5.next(), that'll do the trick given that the data is in one line ONLY. If it's multiple lines then that won't work either.

Categories