Want to add some dynamic values in long json string

897 views Asked by At

I have a very long json data. I am taking it as a string and using http Post to send it

I have to pass some unique values every time therefor i have created some methods to generate unique values.

Below is some of the part of json data.

\\\\\\\"timestamp\\\\\\\" : \\\\\\\"2015-01-27 22:55:30.941292+00\\\\\\\" [You can see so many slashes here [four slashes \\\\ are automatically added when i copy paste the json to my intellij]

I have created a method which returns timeStamp.

So i want to add it as a variable in json string. And i am doing that as below.

\\\\\\\"timestamp\\\\\\\" : "+timeStamp+"

but when i do that and httppost it and print the json created and then compare it on online json validator there is a difference in the hardcoded json data and data generated after concatinating the varaible.

I have used json beautify, remove the slashes or whitespaces. But somehow json data is distorted.

Could you please specify the way i should handle the very-very long json data as when i copy the provided json data to my intellij. it by itlself also add \n and more slashes.

Also please provide your comments on below that how should i concatenate the variable with so many slashes

\\\\\\\"timestamp\\\\\\\" : "+timeStamp+"

1

There are 1 answers

0
Aaron Digulla On

JSON isn't very suited for modification (like any other serialization format). The correct way to do it is to parse the JSON into an object (probably a map of some kind), make the modifications and create a JSON string again.

If you really want to avoid this step, you can use a regexp to replace part of the JSON string with a new value:

Pattern pattern = Pattern.compile("(\"timestamp\": )\"[^\"]+\"");
Matcher matcher = pattern.match(json)
String newValue = matcher.replaceFirst("\\1\"" + timeStamp + \");

This will replace the value of the timestamp property instead of creating something like "key": "value""value" which isn't legal JSON. Note that the timestamp needs to be quoted in JSON and it must have the exact format which the recipient expects - the recipient won't magically understand something which you think could be a timestamp.