add custom property when writeValueAsString(object) - java

I have a id(Long) that js can not handle it. So when when I return id, I want to return another property id_str.
Just like :
{"id":43777753494847488, "id_str":"43777753494847488"}
I am using fastxml jackson writeValueAsString(object) method.
What should I do?

fail to rewrite the JsonSerializer. Maybe it's to hard for me. So I modify the json string. here is the code:
public static String expandUserIDStr(String json) {
String key = "user_id";
String expandKey = "user_id_str";
String r = "\"" + key + "\":(\\d+)[,]{0,1}";
Pattern patter = Pattern.compile(r);
Matcher matcher = patter.matcher(json);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
String expandContent = "\"" + expandKey + "\":\"" + matcher.group(1) +"\"," + matcher.group(0);
System.out.println(expandContent);
matcher.appendReplacement(buffer, expandContent);
}
matcher.appendTail(buffer);
return buffer.toString();
}

Related

How to convert a Java string against a pattern regex?

I want to convert a component version (for example 2.6.0) to this form G02R06C00. I think it's possible with regex and pattern with Java but I don't found how. I have seen examples to match a string against a pattern (in this case the regex would be G\d\dR\d\dC\d\d I guess), but I don't find how to convert a string to other string with a pattern. Thanks in advance.
What I have done is:
String gorocoVersion = version.replaceAll("(\\d*)\\.(\\d*)\\.(\\d*)", "G$1R$2C$3");
that produces G2R6C0, it's missing yet to add 0 to match 2 digits.
So, I have to split input string before and I can't anymore use replaceAll, that's why I was looking for more clever option that automatically add 0 before simple digit too according to the output pattern G\d\dR\d\dC\d\d, like we can find in word or excel
Something that works with snapshot version but it's very ugly :
/**
* #return version in G00R00C00(-SNAPSHOT) format.
*/
private String formatVersion() {
String gorocoVersion = "";
if (StringUtils.isNotBlank(version)) {
String[] versionTab = version.split("\\.");
String partG = String.format("%02d", Integer.parseInt(versionTab[0]));
String partR = String.format("%02d", Integer.parseInt(versionTab[1]));
String partC = versionTab[2];
String snapshotSuffix = "-SNAPSHOT";
if (partC.endsWith(snapshotSuffix)) {
partC = String.format("%02d",
Integer.parseInt(partC.substring(0, partC.indexOf('-')))) + snapshotSuffix;
} else {
partC = String.format("%02d", Integer.parseInt(partC));
}
gorocoVersion = "G" + partG + "R" + partR + "C" + partC;
}
return gorocoVersion;
}
Try this method:
private static String formatVersion(String version) {
Pattern pattern = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)(-SNAPSHOT)*$");
Matcher matcher = pattern.matcher(version);
if (matcher.find()) {
return String.format("G%02dR%02dC%02d", Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(3)));
} else {
throw new IllegalArgumentException("Unsupported version format");
}
}
Output for the version param value 2.6.0:
G02R06C00
Thanks a lot Ilya, here my final code which accepts SNAPSHOT and also x.y versions :
private String formatVersion(String version) {
if (StringUtils.isNotBlank(version)) {
Pattern pattern = Pattern.compile("^(\\d+)\\.(\\d+)\\.?(\\d+)?(-\\w*)?");
Matcher matcher = pattern.matcher(version);
if (matcher.find()) {
return String.format("G%02dR%02dC%02d%s", Integer.parseInt(matcher.group(1)),
Integer.parseInt(matcher.group(2)),
matcher.group(3) != null ? Integer.parseInt(matcher.group(3)) : 0,
matcher.group(4) != null ? matcher.group(4) : "");
}
}
return version;
}
With this code 2.6 gives G02R06C00 and 2.6.1-SNAPSHOT gives G02R06C01-SNAPSHOT, perfect :)

How can I get the string element from the format string using regular expression?

My input string is like this :
String msgs="<InfoStart>\r\n"
+ "id:1234\r\n"
+ "phone:912119882\r\n"
+ "info_type:1\r\n"
+<InfoEnd>\r\n"
+"<InfoStart>\r\n"
+ "id:5678\r\n"
+ "phone:912119881\r\n"
+ "info_type:1\r\n"
+<InfoEnd>\r\n";
Now I can use the regular expression to get the info array :
private static Pattern patter= Pattern.compile("InfoStart>([\\s\\S]*?)<InfoEnd>");,But how to get the id,phone using regular expression?I try to write the code,but it fail,how to fix it?
private static Pattern infP = Pattern.compile("<InfoStart>([\\s\\S]*?)<InfoEnd>");
private static Pattern lineP = Pattern.compile(".*?\r\n");
final java.util.regex.Matcher matcher = patter.matcher(msgs);
while (matcher.find()){
String item = matcher.group(1);
Matcher matcherLine = lineP.matcher(item);
while(matcherLine.find()){
if(matcherLine.groupCount()>0){
String value= matcherLine.group(1);
int firstIndex=value.indexOf(":");
System.out.println("key:"+value.substring(0, firstIndex)+"value:"+value.substring(firstIndex+1));
}
}
}
Perhaps you can try this:
Pattern xmlPattern = Pattern.compile("<InfoStart>\\s+id:(\\d+)\\s+phone:(\\d+)\\s+info_type:(\\d+)\\s+<InfoEnd>");
Matcher matcher = xmlPattern.matcher(msgs);
while (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println(matcher.group(3));
}
The output:
1234
912119882
1
5678
912119881
1
But still I have to as say as Tim Biegeleisen mentioned, you'd better use other way around to parse a XML string.
Besides, your input string is incorrect, it should be:
String msgs="<InfoStart>\r\n"
+ "id:1234\r\n"
+ "phone:912119882\r\n"
+ "info_type:1\r\n"
+ "<InfoEnd>\r\n" // you lack an open double quote;
+"<InfoStart>\r\n"
+ "id:5678\r\n"
+ "phone:912119881\r\n"
+ "info_type:1\r\n"
+ "<InfoEnd>\r\n"; // you lack an open double quote;

Best way to split a string containing question marks and equals

Having an issue where I have a java string:
String aString="name==p==?header=hello?aname=?????lname=lastname";
I need to split on question marks followed by equals.
The result should be key/value pairs:
name = "=p=="
header = "hello"
aname = "????"
lname = "lastname"
The problem is aname and lname become:
name = ""
lname = "????lname=lastname"
My code simply splits by doing aString.split("\\?",2)
which will return 2 strings.One contains a key/value pair and the second string contains
the rest of the string. If I find a question mark in the string, I recurse on the second string to further break it down.
private String split(String aString)
{
System.out.println("Split: " + aString);
String[] vals = aString.split("\\?",2);
System.out.println(" - Found: " + vals.length);
for ( int c = 0;c<vals.length;c++ )
{
System.out.println(" - "+ c + "| String: [" + vals[c] + "]" );
if(vals[c].indexOf("?") > 0 )
{
split(vals[c]);
}
}
return ""; // For now return nothing...
}
Any ideas how I could allow a name of ?
Disclaimer: Yes , My Regex skills are very low, so I don't know if this could be done via a regex expression.
You can let regex do all the heavy lifting, first splitting your string up into pairs:
String[] pairs = aString.split("\\?(?!\\?)");
That regex means "a ? not followed by a ?", which gives:
[name==p==, header=hello, aname=????, lname=lastname]
To then also split the results into name/value, split only the first "=":
String[] split = pair.split("=", 2); // max 2 parts
Putting it all together:
String aString = "name==p==?header=hello?aname=?????lname=lastname";
for (String pair : aString.split("\\?(?!\\?)")) {
String[] split = pair.split("=", 2);
System.out.println(split[0] + " is " + split[1]);
}
Output:
name is =p==
header is hello
aname is ????
lname is lastname
You can try like this
String[] vals = "Hello??Man?HowAreYou????".split("\\?+");
System.out.println(vals[0]+vals[1]+vals[2]);
OUTPUT
HelloManHowAreYou
But as aname=????? you want to get you can replace the
????? Five Question Marks with Other Symbol and replace back to ????? after split
String processed="Hello????Good? ? ....???".replace("????","*");
OUTPUT
Hello*Good? ? ....???
And than use split for ?
Here the code, you are looking .
Implemented using the Split and HashMap.
Tested and Executed.
import java.util.HashMap;
import java.util.Map;
public class Sample {
public static void main(String[] args) {
// TODO Auto-generated method stub
// String[] vals = "Hello??Man?HowAreYou????".split("\\?+");
// System.out.println(vals[0]+vals[1]+vals[2]);
String query="name==p==?header=hello?aname=?????lname=lastname";
String[] params = query.split("\\?");
Map<String, String> map = new HashMap<String, String>();
for (String param : params)
{
String name = param.split("=")[0];
String value = param.substring(name.length(),param.length());
map.put(name, value);
System.out.println(name);
if(name.equals("")){
value+="?";
}
System.out.println(value.replaceAll(" ", ""));
}
}
}
I assume you are parsing URLs. The correct way would be to encode all special characters like ?, & and = which are values or names.
Better Solution: Encoding characters:
String name = "=p==";
String aname = "aname=????";
String lname = "lastname";
String url = "name=" + URLEncoder.encode(name, "UTF-8") +
"?aname=" + URLEncoder.encode(aname, "UTF-8") +
"?lname=" + URLEncoder.encode(lname, "UTF-8");
After that you have something like this:
name==p==?aname=?????lname=lastname
This can be splitted and decoded easily.
Other Solution: Bad input parsing:
If you insist, this works also. You can use a regex:
Pattern pattern = Pattern.compile("(\\w+?)=(\\S+?\\?+)");
Matcher m = pattern.matcher(query + "?");
while (m.find()) {
String key = m.group(1);
String value = m.group(2);
value = value.substring(0, value.length() - 1);
System.out.println(key + " = " +value);
}

Java. Replace relative Links to absolute with regex

I want to replace in a String, which represents a Html-File,all relative Links with absolute Links. I write the following method, which does not work. any links are followed by a duplicate baseurl like http://www.google.dehttp://www.google.de/resource?
public static String replacePattern(URL targetUrl,String urlAsString,String patternString) throws IOException{
System.out.println(targetUrl.toString());
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(urlAsString);
Set<String> replacedStrings = new TreeSet<String>();
//return matcher.replaceAll(targetUrl.toString()+"$0");
while (matcher.find()) {
String relativeLink = matcher.group(1);
//System.out.println("Find Link " + relativeLink);
if(!replacedStrings.contains(relativeLink)){
//System.out.println("Relative Link " + relativeLink);
String newLink = targetUrl.toString() + relativeLink;
//System.out.println("New Link " + newLink);
urlAsString = urlAsString.replace(relativeLink,newLink);
replacedStrings.add(relativeLink);
}
}
return urlAsString;
}
UrlAsString is a String which contains the wholecontent as a String.My patterns are
href=['\"](/[^'\"]+)['\"]
and
src=['\"](/[^'\"]+)['\"]
Use Class URL:
URL baseUrl = new URL("http://www.domain.com/folder/");
URL url = new URL(baseURL , "url.html");

java regular expression

I have a string like this
STAR=20110209
00:01:01|PNAM=test_.xml|PNUM=480|SSTA=20110209
00:01:01|STRT=20110209
00:01:01|STOP=20110209 00:01:01|
and i want to extract values of few of the keys here.
like whats the value of PNAM and SSTA.
I want a regular expression that can provide the values of few of the keys and keys can be in any order.
Would something like this work for you?
String str = "STAR=20110209 00:01:01|PNAM=test_.xml|PNUM=480|SSTA=20110209 00:01:01|STRT=20110209 00:01:01|STOP=20110209 00:01:01";
String[] parts = str.split("\\|");
for (String part : parts)
{
String[] nameValue = part.split("=");
if (nameValue[0] == "somekey")
{
// ..
}
}
So, the way your problem is really isn't best solved with regular expressions. Instead, use split() like someone else has offered, but instead of having a crazy if loop, load everything into a map.
String str = "STAR=20110209 00:01:01|PNAM=test_.xml|PNUM=480|SSTA=20110209 00:01:01|STRT=20110209 00:01:01|STOP=20110209 00:01:01";
String[] parts = str.split("|");
Map<String, String> properties = new HashMap<String, String>();
for (String part : parts) {
String[] nameValue = part.split("=");
properties.put(nameValue[0], nameValue[1]);
}
Then all you have to do is, properties.get("PNUM")
Use this Java code:
String str = "STAR=20110209 00:01:01|PNAM=test_.xml|PNUM=480|SSTA=20110209 00:01:01|STRT=20110209 00:01:01|STOP=20110209 00:01:01|";
Pattern p = Pattern.compile("([^=]*)=([^|]*)\\|");
Matcher m = p.matcher(str);
String pnamVal = null, sstaVal = null;
while (m.find()) {
//System.out.println("Matched: " + m.group(1) + '=' + m.group(2));
if (m.group(1).equals("PNAM"))
pnamVal = m.group(2);
else if (m.group(1).equals("SSTA"))
sstaVal = m.group(2);
if (pnamVal != null && sstaVal != null)
break;
}
System.out.println("SSTA: " + sstaVal);
System.out.println("PNAM: " + pnamVal);
OUTPUT
SSTA: 20110209 00:01:01
PNAM: test_.xml

Categories