in the test I have to get the product version and build number but they are in different lines, and have an extra suffix that needs to be removed.
I can not cope with this task, can you help?
JsonObject versionConfig = read("config","version",user.userName, user.password);
version=versionConfig.get("buildNumber").getAsString();
json answer
{
"version": "1.1-SNAPSHOT",
"branch": "1111",
"buildNumber": "666",
"date": "01.01.2020"
}
everyone understands what I am getting only version=666
but in the end I need to get
version=1.1.666
do not swear, I worked as a system administrator for 3 years, and I'm only learning Java, and with parsing, Json did not work at all, this is the best that I could
You can get your version and replace "Version" by your buildNumber:
String version = versionConfig.get("version").getAsString();
String buildNumber = versionConfig.get("buildNumber").getAsString();
String result = version.replace("Version",buildNumber);
//1.1-Version => 1.1-666
Related
I have a json string where all the values need to be surrounded with double quotes. for example (just a sample, it contains many similar fields)
{"Id": "2017",
"Currency": "AUD",
"Date": 2020-06-22,
"InCash": 0.000,
"Dep": "ABC90",
"sumCash": 770.87,
"AnotherDate": 2020-06-21}
to
{"Id": "2017",
"Currency": "AUD",
"Date": "2020-06-22",
"startCash": "0.000",
"Dep": "ABC90",
"sumCash": "770.87",
"AnotherDate": "2020-06-21"}
I am trying with regular expressions but its breaking the 'Date' fields.
jsonString.replaceAll(":[ ]*([\\w#\\.]+)", ": \"$1\"")
also tried with gson library, but its only putting the quotes on date values and not on the decimal values.
new JsonParser().parse(jsonString).toString()
What exactly I need to do to achieve it?
check this out
var newS = jsonString.replaceAll(": +((?!\\\\).*)(!?[,|}] *)", ": \"$1\"$2").replaceAll("\\\"\\\"","\"");
output
{
"Id": "2017",
"Currency": "AUD",
"Date": "2020-06-22",
"InCash": "0.000",
"Dep": "ABC90",
"sumCash": "770.87",
"AnotherDate": "2020-06-21"
}
if the other JSON form (rules) of yuior string don't change, this will work for the
name - value form.
note - i did not do the part where it could be a string in a list but its doable alsero
Find:
("\s*\w+\s*"\s*:(?!\s*")(?!\s*\d+\s*(?:,|\]|}))(?!\s*[{\[])(?!\s*(?:true|false|null)\s*(?:,|\]|}))\s*)(.+?)(?=[,}])
Replace:
$1"$2"
demo
see my complete PCRE regex for parsing JSON a eally simple structure spec.
here https://regex101.com/r/H8datD/1 which is not available to java until regex engine uses recursion (functions).
note - when needing to change just one aspect of JSON where it otherwise is complient with the spec structure
it is easy to extract the code in my regex to get right down to the area of interest. it easy !
Got it working with the below regex expression.
jsonString.replaceAll(": [ ]*([\\w#\\.-]+)", ": \"$1\""));
Thanks everyone for your help and support !
I'm looking to dump, rather toString() a section of JSON that I want to store locally as a string, since it it is highly variable and not imperative for me to know the contents.
I'm using JsonReader for the parsing:
https://developer.android.com/reference/android/util/JsonReader.html
Unfortunately, when I reach the token that contains what I want to dump, JsonReader does not have a method for dumping the entire JSON to a string.
This is the closest that it has:
https://developer.android.com/reference/android/util/JsonReader.html#toString()
It seems that I may have to use regex to pull out the value of the token I am targeting.
Is there another, better solution? How would I do this with regex?
Assume that this is the sample JSON and I am targeting the user key:
{
"id": 912345678901,
"text": "How do I read JSON on Android?",
"geo": null,
"user": {
"name": "android_newb",
"followers_count": 41
}
}
I have this JSON:
{
"header":
{
"IssuerID": "000141",
"AuthenticationID": "e07020c0d040a050a0808099",
"AuthenticationDateTime": "20151103093035",
"AuthenticationDateTimeGMT": "20151103093035",
"Signature": "MThEMTExQkMzQzM0OUIxQjM5MDc2MjFGMzMyQjhDNTk1OTI0NDNERTg5ODcwQjNFOTc0ODQwNThBNkQxNTgzNTk2N0YzN0I2OTkyMzI1QjY2OENDQjgxRUNERDlGNDFDNzVCMzQ5Njg5NTY4NzkwNUQ5MzBDN0ExOTVGOUY0OUY2QjlCQzlDQkREOEQ3NjEzRkQ2OEYyMDhEQTY2QTkzNUZDM0UzOTI3RDk2OTYwODg4NTkyNzYyQUJCQkJFREZGNzNCNEEyNUU5OTc5OTFFODk2MTQ0Q0Y4Q0RGNzg1M0JBQTM4QkZBQzRFRUY2MTkzM0E4REI3QkQ0MEJBRkU4OTlEOTVDNTkxOTQ0M0IwNjMyMzZDQ0U4MzdBQTQzODU3RkMyOEQ0Rjk2NUMyRkNERUM0NDREQkIzNUM0QUVERDUzRjFBOTk5RTQ4Mjk4MzNERjU3RTQ1QUE2Nzc4MDUyRTdERTdGRTVFRURGRkVGMTlFN0Y2QTAyQTVCNjk3NUU2OUNGRUU3MzRGNDZDOTE0Q0U3NTk5NzdGNDkyOTdFQkRGREIwNDBCNDhBQTkzMzE1QjU0MzI1Njk0MjgxMjVDMzM5OUM3MTExNTg4NENBOTU3QTM4OTU5MTY5OTQ1NkQ2NDNFOUVEMjU5MjRDNzhEMDQxMEJGM0ZEQUVFM0Y1QTU="
},
"body":
{
"TransactionDateTime": "0151103093035",
"TransactionID": " SP020110216",
"IASauthenticationRequestReferenceID": "h0IrqhqBoUpUCiSv17NB0vHvABIUxHGCurJZFzUWdZJz9TxYio",
"VerificationID": "h0IrqhqBoUpUCiSv17NB0vHvABIUxHGCurJZFzUWdZJz9TxYio ",
"Acquirer_id": "000014",
"MerchantName": " Twin Hotel ",
"CurrencyCodeISO": "360",
"Amount": "970000.00",
"CardNumber": " BmaHLuFRg4SaPnaGB07t5fNrHXr/lyOa ",
"AuthenticationResponseCode": "00",
"AuthenticationResponseDetails": "Success",
"ValidityDateTimeExpireGMT": "20151103094035",
"Expiry_Period": "10"
}
}
How can I validate this json? For example, issuer id must be integer and have min and max values and if someone put headers instead of header it can get result: "json not valid".
I'm using java and json.org.simple for parsing.
Can anyone help me?
If you are looking for real schema validation you might want to have a look at http://json-schema.org/. There are validators for most common languages.
Assuming there are classes to represent the above structure you could try to use Java Bean Validation.
In your case, I would use a deserializer like jackson and not a json-schema, since you seem to have integer and dates encoded as string in your json. Thus, in a json-schema you would need to define strange regex. To see how to use jackson and to weigh the pros and cons of each method you can take a look a my blog post here: Three Ways to Validate JSON in Java
Morning,
Seem to be having a brainfart! Have had a look around and can't see any one else having the same issue so I've either completely missed something (most likely) or nobody else has this use case.
I basically want to return all objects stored in a mongodb collection, including their id's, however as the string representation rather than the full object. So this:
public ArrayList findAllObjects(){
return db.getCollection("objects").find().into(new ArrayList<Document>());
}
{
_id: {
class: "org.bson.types.ObjectId",
counter: 7230903,
date: "2016-10-03T12:39:38Z",
machineIdentifier: 5652488,
processIdentifier: 8859,
time: 1475498378000,
timeSecond: 1475498378,
timestamp: 1475498378
},
name: "Test Object"
},
Now if I run a find on the mongo console I get something along the lines of:
{
"_id": ObjectId("57f2518a564008229b6e55b7"),
"name": "Test Object"
}
It's this 57f2518a564008229b6e55b7 that I'd like to return in the original json as the _id (potentially could add under another name) field.
I can get that string representation in the java code simply by running get getObjectId() on an individual document. So I could possibly loop through every result and set/add the _id but that feels like a bit of a smell to me.
Any suggestions would be welcome.
Thanks
Update:
Thanks Sinclair for the comments, I don't believe this is a duplicate though, as I do actually want to include the id not necessarily exclude anything. If the string representation was in the org.bson.types.ObjectId object as a property I could then potentially exclude the rest but that isn't the case.
You can convert the object to string simply using the toString() method:
List<Document> documents = collection.find().into(new ArrayList<>());
documents.parallelStream().forEach(document -> {
document.put("_id", document.get("_id").toString());
});
I have a string response like below which is a invalid json as it contains "obj13=".I want to convert it to a JSONObject(JAVA) and use it.Is there any good way to convert it to JSONObject without using String split operation.
obj13={
players: [
{
name: "rocky",
place: "brazil",
age: "21",
},
{
name: "andy",
place: "New Zealand",
age: "23",
}
]
}
This is, of course, JavaScript, not JSON. If you can, I would go back to the service provider and ask for a JSON response.
If the format of the string is consistent, you could just use:
json=json.substring(json.indexof('=')+1);
and then parse the result. Note that most good parsers should have an option to allow the keywords without quotes and to allow the extraneous commas (mine does, but unfortunately for you it doesn't create JSONObject's but is of a lower level - it's designed to construct the data-structure of the caller's choice, which could be a JSONObject if that's what you wanted but you'd have to code it).
If the result may or may not have the assignment, you may want to get a bit fancier and ensure that the non-whitespace characters before the '=' are valid for a JS identifier and the first non-whitespace after it is '{'.