How to convert JSON Array String to Set in java - json

I have a JSON Array string like [1,2].I want to convert this in to Set.How can I do it in java 8 ?
This is my code
String languageStr = rs.getString("languages");
jobseeker.setLanguageIds(StringUtils.isEmpty(languageStr) ? null
: Arrays.stream(languageStr.split(","))
.map(Integer::parseInt)
.collect(Collectors.toSet()));
Getting error like this
java.lang.NumberFormatException: For input string: " 2"
The space in json array is the problem.Is there any solution?
This is my code after changes
String languageStr = rs.getString("languages");
String languages=languageStr.substring(1,languageStr.length()-1);
jobseeker.setLanguageIds(StringUtils.isEmpty(languages) ? null
: Arrays.stream(languages.split(","))
.map(String::trim)
.map(Integer::parseInt)
.collect(Collectors.toSet()));
Can I get the output in any other way withot using these 2 steps:
languages=languageStr.substring(1,languageStr.length()-1);
.map(String::trim)

You can use the trim method to remove leading and trailing withespace before parse it to Integer.
So your code will be this
Arrays.stream(languageStr.split(","))
.map(String::trim)
.map(Integer::parseInt)

Finally I got the solution
Changed code like this:
String languageStr = rs.getString("languages");
Set<Integer> languages = mapper.readValue(languageStr, typeFactory.constructCollectionType(Set.class, Integer.class));
jobseeker.setLanguageIds(StringUtils.isEmpty(languageStr) ? null : languages);

Using a TypeToken and the Google Gson library, you should be able to do that like below:
String languageJsonStr = rs.getString("languages");
Set<Integer> myLanguageSet = new Gson().fromJson(languageJsonStr, new TypeToken<HashSet<Integer>>(){}.getType());

Related

How to parse json and replace a value in a nested json?

I have the below json:
{
"status":"success",
"data":{
"_id":"ABCD",
"CNTL":{"XMN Version":"R3.1.0"},
"OMN":{"dree":["ANY"]},
"os0":{
"Enable":true,"Service Reference":"","Name":"",
"TD ex":["a0.c985.c0"],
"pn ex":["s0.c100.c0"],"i ex":{},"US Denta Treatment":"copy","US Denta Value":0,"DP":{"Remote ID":"","cir ID":"","Sub Options":"","etp Number":54469},"pe":{"Remote ID":"","cir ID":""},"rd":{"can Identifier":"","can pt ID":"","uno":"Default"},"Filter":{"pv":"pass","pv6":"pass","ep":"pass","pe":"pass"},"sc":"Max","dc":"","st Limit":2046,"dm":false},
"os1":{
"Enable":false,"Service Reference":"","Name":"",
"TD ex":[],
"pn ex":[],"i ex":{},"US Denta Treatment":"copy","US Denta Value":0,"DP":{"Remote ID":"","cir ID":"","Sub Options":"","etp Number":54469},"pe":{"Remote ID":"","cir ID":""},"rd":{"can Identifier":"","can pt ID":"","uno":"Default"},"Filter":{"pv":"pass","pv6":"pass","ep":"pass","pe":"pass"},"sc":"Max","dc":"","st Limit":2046,"dm":false},
"ONM":{
"ONM-ALARM-XMN":"Default","Auto Boot Mode":false,"XMN Change Count":0,"CVID":0,"FW Bank Files":[],"FW Bank":[],"FW Bank Ptr":65535,"pn Max Frame Size":2000,"Realtime Stats":false,"Reset Count":0,"SRV-XMN":"Unmodified","Service Config Once":false,"Service Config pts":[],"Skip ot":false,"Name":"","Location":"","dree":"","Picture":"","Tag":"","PHY Delay":0,"Labels":[],"ex":"From OMN","st Age":60,"Laser TX Disable Time":0,"Laser TX Disable Count":0,"Clear st Count":0,"MIB Reset Count":0,"Expected ID":"ANY","Create Date":"2023-02-15 22:41:14.422681"},
"SRV-XMN Values":{},
"nc":{"Name":"ABCD"},
"Alarm History":{
"Alarm IDs":[],"Ack Count":0,"Ack Operator":"","Purge Count":0},"h FW Upgrade":{"wsize":64,"Backoff Divisor":2,"Backoff Delay":5,"Max Retries":4,"End Download Timeout":0},"Epn FW Upgrade":{"Final Ack Timeout":60},
"UNI-x 1":{"Max Frame Size":2000,"Duplex":"Auto","Speed":"Auto","lb":false,"Enable":true,"bd Rate Limit":200000,"st Limit":100,"lb Type":"PHY","Clear st Count":0,"ex":"Off","pc":false},
"UNI-x 2":{"Max Frame Size":2000,"Duplex":"Auto","Speed":"Auto","lb":false,"Enable":true,"bd Rate Limit":200000,"st Limit":100,"lb Type":"PHY","Clear st Count":0,"ex":"Off","pc":false},
"UNI-POTS 1":{"Enable":true},"UNI-POTS 2":{"Enable":true}}
}
All I am trying to do is to replace only 1 small value in this super-complicated json. I am trying to replace the value of os0 tags's TD ex's value from ["a0.c985.c0"] to ["a0.c995.c0"].
Is freemarker the best way to do this? I need to change only 1 value. Can this be done through regex or should I use gson?
I can replace the value like this:
JsonObject jsonObject = new JsonParser().parse(inputJson).getAsJsonObject();
JsonElement jsonElement = jsonObject.get("data").getAsJsonObject().get("os0").getAsJsonObject().get("TD ex");
String str = jsonElement.getAsString();
System.out.println(str);
String[] strs = str.split("\\.");
String replaced = strs[0] + "." + strs[1].replaceAll("\\d+", "201") + "." + strs[2];
System.out.println(replaced);
How to put it back and create the json?
FreeMarker is a template engine, so it's not the tool for this. Load JSON with some real JSON parser library (like Jackson, or GSon) to a node tree, change the value in that, and then use the same JSON library to generate JSON from the node tree. Also, always avoid doing anything in JSON with regular expressions, as JSON (like most pracitcal languages) can describe the same value in many ways, and so writing truly correct regular expression is totally unpractical.

python RegEx json Double quotes

I got a json through the spider, but the json format has a problem, name:value, the name is missing double quotes. like this:
{ listInfo:[{title:'it is title',url:'http://test.com',imgurl:'http://test.com',imgurl2:'',abstract:'',source:'',pubtime:'2019-05-22 11:47:24'},{title:'xx',url:'http://test.com/1.htm',imgurl:'http://test.com',imgurl2:'',abstract:'',source:'',pubtime:'2019-05-22 07:54:46'}]}
I want add double quotes in "name",and need to exclude String of [http { ...]
{ "listInfo":[{"title":'it is "title"',"url":'http://test.com',...
I tryed this but it is not work
#(.*?)\:(.*?)\n'
pattern = re.compile(r'^((?![http]\").)*\:(.*?)\n', re.MULTILINE )
content = content.replace(pattern.search(content).group(1),'\"'+pattern.search(content).group(1).strip()+'\"')
I also tryed
How to add double quotes to the dictionary?
content = '''
{ listInfo:[{title:'it is title',url:'http://test.com',
imgurl:'http://test.com',imgurl2:'',abstract:'',source:'',
pubtime:'2019-05-22 11:47:24'},{title:'xx',url:'http://test.com/1.htm',
imgurl:'http://test.com',imgurl2:'',abstract:'',source:'',pubtime:'2019-05-22 07:54:46'}]}
'''
# dict_str = lambda data : re.sub(r'(\w+):\s*(-?\d[\d/.]*)',r'"\1": "\2"',data)
dict_str = lambda data : re.sub(r'(\w+):(.*?)\n',r'"\1": "\2"',data)
for i in [content] :
var1=dict_str(i)
print(var1)
the result is look like:
{ "listInfo": "[{title:'it is title',url:'http://test.com',""imgurl": "'http://test.com',imgurl2:'',abstract:'',source:'',""pubtime": "'2019-05-22 11:47:24'},{title:'xx',url:'http://test.com/1.htm',""imgurl": "'http://test.com',imgurl2:'',abstract:'',source:'',pubtime:'2019-05-22 07:54:46'}]}"
Who knows how to write regEx.
Thinks!
I used a comparative method to solve it.
script = script.replace('abstract','\"abstract\"')
...
:(

Split string by commas then Store in array val in Play! + Scala

I am passing a List
errors.add(new ValidationError("Employee " + strId, "error.range," + strName +","+ intRange));
that will build a string
"Employee1","error.format,FIRST NAME,20
I want to split the message string with "," and store it in a array variable in scala template or twirl in view. I'm not really good at scala code i don't know how to store a variable in scala template nor know the syntax in splitting a string. Is there a code that can do this task in scala template?. Thank you.
<div id = "msg-menu" class = "msg-menu">
#for((key, value) <- appModel.errors) {
<div class="error-msg">
<p>#key :
#for(err <- value) {
#for(error <- err.message.split(",")) {
#Messages(error)
}
}
</p>
</div>
}
</div>
What i did was use a for loop to do it but it is not what i needed. i need to declare all the string in an array and use them as parameters on the #Messages. like:
#Messages(error[0],error[1],error[2])
In which error0 = "error.range", error1 = "FIRST NAME" and error2 = "20". In conf/message i will build an error message with the parameters
error.range = Enter {0} in {1} characters or less.
Variables are definined in twirl using #defining, in the following way:
#defining( err.message.split(",").lift ) { errors =>
...
}
The use of lift could be handy, as it helps with index out of bounds conditions where you might not know the exact number of elements in the array / collection. errors(2) will return Some("20") in your example and None if there isn't a value.
Replacing your innermost for loop with the above and hardcoding to exactly 3 parameters, you might then have something like
#defining( errors(0).getOrElse("") ) { messageId =>
#Message(messageId,errors(1).getOrElse(""),errors(2).getOrElse(""))
}

Idiomatic way of converting string of key value pairs to a JSON string (Scala)

I'm trying to convert a string of key value pairs to a JSON string. The only thing I know about the string of KV pairs is the format of the string i.e. space seperated, comma seperated etc.. For e.g. I don't control over the number or type of the keys coming in as input.
Here is what I came up with and wanted to see if this approach looks OK / awesome / awkward. Would appreciate if there is better alternative than this.
INPUT : clientIp="1.1.1.1" identifier="a.b.c" key1=10 key2="v3"
final val KV_PATTERN = "(\"[^\"]*\"|[^,\\\"\\s]*)=(\"[^\"]*\"|[^,\\\"\\s]*)".r
val cMap = KV_PATTERN.findAllMatchIn(inputString).map(m => (m.group(1).trim(), m.group(2).trim())).toMap
val json = cMap.map { case (key, value) => if (!key.startsWith("\"")) s""""$key"""" + ":" + value else s"$key:$value" }.mkString("{", ",", "}")`
OUTPUT: {"clientIp":"1.1.1.1","identifier":"a.b.c","key1":10,"key2":"v3"}
"{"+ inputString.split(" ").map{case i => val t = i.split("="); s""""${t(0).replaceAll("^\"|\"$", "")}": ${t(1)}"""}.mkString(",") + "}"
Maybe this is more cleaner.

Use string as a JSON command

I have this string:
var test = "toAdd";
I want to use it to extract data from JSON, like:
console.log(value.stats.test);
As you see, test is not correct, as it is just a string and can't be used, it is just not recognized at all. How do I make it recognize?
What you are attempting to do is this:
var someVar;
someVar.test = 'Sample';
someVar.test.attribute = 'Another sample';
// this:
console.log(someVar['test']['attribute']);
// will produce the same as this:
console.log(someVar['test'].attribute);
// as well as the same as this:
console.log(someVar.test['attribute']);
This will print "Another sample".
This has nothing to do with JSON. This is just javascript, and like anything where the . notation won't work switch to array notation:
foo.bar.baz = 'qux';
alert(foo['bar'].baz); // popup with 'qux'
^-----^-- note these
In your case, value.stats[test]. Now "test" isn't an array key, it's a variable whose value gets used as the key.