Join a json String values with new line - java

I need to return json array each element in new line. but instead it's printing in one line. I tried using '/n' and space but it's not working.
String json = null;
//split cookie with delimiter to store in array
String wl[] = wishList.split("~");
//JSON RETURN VALUE
json = "[\"";
for(int i = 0; i < wl.length; ++i) {
json += wl[i];
//tried but didn't work
//json.split("\n");
}
json += "\"]";
System.out.println(json);
so i tried cancatinating in for loop but it didn't work.
I need out like this
1.abc
2.bcd
3.efg
but i'm getting this output
1.abcbcdefg

What you are trying to do (if I get it right) is to split a String on the ~ and creating a JSON array with it (one separate line).
Did you thought about simply replacing the character ?
String json = "[" + wishlist.replace("~", ",\n") + "]"; //Added a , to separated each elements
But if you want to do it yourself,
String json = "[";
for(int i = 0; i < wl.length; ++i) {
json += wl[i] + ",\n";
}
json += "]";
You need to add the newLine character, not split it again.
Off course, as pointed, this should be done using a Library design to do it but here is a simple correction of you code.
PS : I didn't write the needed \" for redability. But this can be easily added in both solutions.

I tried using '/n' and space but it's not working.
You should use "\n" in your JSON String to add new line and not "/n", it is not the same thing. You should do the same thing for the regex pattern.
3. Line Separator is '\n'
This means '\r\n' is also supported because trailing white space is ignored >when parsing JSON values.
The last character in the file may be a line separator, and it will be
treated the same as if there was no line separator present.
Source : http://jsonlines.org/
Edit
A Json array has comma to separate values of the array and string should be between quotes or double quotes. but doesn't need "\" at the begining and at the end.
You could get this String :
["abc",
"bcd",
"efg"]
with this code :
final String STRING_DOUBLE_QUOTE="\"";
String json = null;
// split cookie with delimiter to store in array
String wl[] = wishList.split("~");
// JSON RETURN VALUE
json = "[";
for (int i = 0; i < wl.length; ++i) {
if (!json.equals("[")) {
json += ",\n";
}
json += STRING_DOUBLE_QUOTE + wl[i] + STRING_DOUBLE_QUOTE;
}
json += "]";
System.out.println(json);

If you want it to be on multiple lines, you're gonna have to save it in multiple elements i.e. an array.
Try this:
String wl[] = wishList.split("~");
for(int i = 0; i < wl.length; ++i){
System.out.println(wl[i]);
}
Unsure if this is what you're asking for, but this is the answer to your written question

Related

Load CSV and split attributes

I'm trying to load a csv file and split 'timespan' into 'begin' and 'end'. If the timespan consists of one date 'begin' and 'end' are the same.
timespan,someOtherField, ...
27.03.2017 - 31.03.2017,someOtherValue, ...
31.03.2017,someOtherValue, ...
Result:
begin,end,someOtherField
27.03.2017,31.03.2017,someOtherValue, ...
31.03.2017,31.03.2017,someOtherValue, ...
At the moment I'm loading the file line by line using OpenCSV. This works pretty good but i don't know how to split one attribute. Propably I have to parse the CSV into an array?
For any line l you can use StringTokenizer to get the tokens separated by ,:
StringTokenizer tokens = new StringTokenizer(l, ",")
The first token represents timespan, so:
String timespan = tokens.nextToken()
Then you can split timespan based on " - ", so:
String[] startEnd = timespan.split(" - ");
Finally, you have to compute the size of the startEnd, if startEnd.length == 1, then you absolutely know that start begin and end coincides, so startEnd[0],startEnd[0]
otherwise the result would look like the following startEnd[0],startEnd[1]
I hope this could help you solve the problem.
Thanks for your answer! I parsed the csv into an extra class and created an object for each record. The code below shows the splitting of the timespan. I will now rebuild a new csv file from all objects.
// Load CSV as Booking objects
ArrayList<Booking> bookings = Utils.readCSV(csvClean);
for (int i = 0; i < bookings.size(); i++) {
String timespan = bookings.get(i).getTimespan();
String begin = "";
String end = "";
if (timespan.contains(" - ")) {
// Split timespan and set values
String[] parts = timespan.split(" - ");
begin = parts[0].trim();
end = parts[1].trim();
bookings.get(i).setBegin(begin);
bookings.get(i).setEnd(end);
} else {
bookings.get(i).setBegin(timespan.trim());
bookings.get(i).setEnd(timespan.trim());
} // end if else
} // end for

How to merge many List<String> elements in one based on double quote delimiter in java

I have a CSV file generated in other platform (Salesforce), by default it seems Salesforce is not handling break lines in the file generation in some large text fields, so in my CSV file I have some rows with break lines like this that I need to fix:
"column1","column2","my column with text
here the text continues
more text in the same field
here we finish this","column3","column4"
Same idea using this piece of code:
List<String> listWords = new ArrayList<String>();
listWords.add("\"Hi all");
listWords.add("This is a test");
listWords.add("of how to remove");
listWords.add("");
listWords.add("breaklines and merge all in one\"");
listWords.add("\"This is a new Line with the whole text in one row\"");
in this case I would like to merge the elements. My first approach was to check for the lines were the last char is not a ("), concatenates the next line and just like that until we see the las char contains another double quote.
this is a non working sample of what I was trying to achieve but I hope it gives you an idea
String[] csvLines = csvContent.split("\n");
Integer iterator = 0;
String mergedRows = "";
for(String row:csvLines){
newCsvfile.add(row);
if(row != null){
if(!row.isEmpty()){
String lastChar = String.valueOf(row.charAt(row.length()-1));
if(!lastChar.contains("\"")){
//row += row+" "+csvLines[iterator+1].replaceAll("\r", "").replaceAll("\n", "").replaceAll("","").replaceAll("\r\n?|\n", "");
mergedRows += row+" "+csvLines[iterator+1].replaceAll("\r", "").replaceAll("\n", "").replaceAll("","").replaceAll("\r\n?|\n", "");
row = mergedRows;
csvLines[iterator+1] = null;
}
}
newCsvfile.add(row);
}
iterator++;
}
My final result should look like (based on the list sample):
"Hi all This is a test of how to remove break lines and merge all in one"
"This is a new Line with the whole text in one row".
What is the best approach to achieve this?
In case you don't want to use a CSV reading library like #RealSkeptic suggested...
Going from your listWords to your expected solution is fairly simple:
List<String> listSentences = new ArrayList<>();
String tmp = "";
for (String s : listWords) {
tmp = tmp.concat(" " + s);
if (s.endsWith("\"")){
listSentences.add(tmp);
tmp = "";
}
}

Junk characters "&#7;" are added and stopping application tool tip functionality to work

Tool tip- functionality is working fine for 1 object but when more object get add at that time it fails.
In catalina.out objects are displayed with no junk characters but when I look in UI via f12, I can see junk character "&#7;".
In java code I used replaceAll and split but no success.
Code-
sHasCP1+="ISS-0000430&#7;ISS-0000434&#7;ISS-0000435&#7;ISS-0000436";
//sHasCP1 = sHasCP1.replace("&#7;" , ";");
//sHasCP1 = sHasCP1.replace("[^a-zA-Z0-9]" , " ");
String[] seperator = new String[50];
seperator = sHasCP1.split("&#7;");
List<String> list = (List) Arrays.asList(seperator);
StringBuilder name = new StringBuilder();
//display elements of List
System.out.println("String array converted to List");
for(int i=0; i < list.size(); i++){
name.append(list.get(i));
if ( i != list.size()-1){
name.append(", ");
}
System.out.println(name.toString());
}
and I am passing name value in title -
sbOut.append("<img src=\"..conCP.gif\" border=\"0\" title=\""+name+ "\"/>");
Not knowing where and when the HTML entity is introduced; the following should do:
final String REPLACEMENT = "\t"; // Or ""?
sHasCP1 = sHasCP1.replace("&#7;", REPLACEMENT);
sHasCP1 = sHasCP1.replace("", REPLACEMENT);
sHasCP1 = sHasCP1.replace("\u0007", REPLACEMENT);
In a first version I leave a TAB character instead. ", " or so would do too.
Nicer would be to inspect/debug/log the exact string.

Inserting Newline character before every number occurring in a string?

I have String of format something like this
String VIA = "1.NEW DELHI 2. Lucknow 3. Agra";
I want to insert a newline character before every digit occurring succeeded a dot so that it final string is like this
String VIA = "1.NEW DELHI " +"\n"+"2. Lucknow " +"\n"+"3. Agra";
How can I do it. I read Stringbuilder and String spilt, but now I am confused.
Something like:
StringBuilder builder = new StringBuilder();
String[] splits = VIA.split("\d+\.+");
for(String split : splits){
builder.append(split).append("\n");
}
String output = builder.toString().trim();
The safest way here to do that would be go in a for loop and check if the char is a isDigit() and then adding a '\n' before adding it to the return String. Please note, I am not sure if you want to put a '\n' before the first digit.
String temp = "";
for(int i=0; i<VIA.length(); i++) {
if(Character.isDigit(VIA.charAt(i)))
temp += "\n" + VIA.charAt(i);
} else {
temp += VIA.charAt(i);
}
}
VIA = temp;
//just use i=1 here of you want to skip the first charachter or better do a boolean check for first digit.

Parsing String Java

I got a String:
["4fd1cf1783353a15415","4ffecf87fcc40d110a965626"]
or
["4fd5f684815345","4fd6ef3e60a676854651","4fd83c33c19164512153"]
And I'd like to store every id (eg. 4fd5f684815345, 4fd6ef3e60a676854651, 4fd83c33c19164512153...) in a independant String (or ArrayList).
How to parse it, because the String can be dynamic (1,2,3 values or more)?
OR JSON Array Parsing:
My JSON
"idCards":[
"4fc52f95egvt418541515",
"4fd1d05454151541545115"
],
A part of my code:
msg3 = (JSONArray) myobject.get("idCards");
System.out.println(msg3.toJSONString());
The result:
[4fc52f95egvt418541515","4fd1d05454151541545115"]
I'd like this 2 values in 2 differents String.
Many thanks for your help!
It would appear to be that this could be a JSON String. In which case, you may make use of a Java JSON Library to help you parse that into Java native objects.
http://www.json.org/
http://code.google.com/p/google-gson/
String data = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
// parse JSON String to JSON Array
JsonArray array = (JsonArray) (new JsonParser()).parse(data);
// build a Java ArrayList
List<String> stringList = new ArrayList<String>();
// for each item in JsonArray, add to Java ArrayList
for (int i = 0; i < array.size(); i++) {
stringList.add((array.get(i)).getAsString());
}
I fully agree with the JSON answers, but if this is a one-off hack, you could just do this:
String input = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
input = input.replace("[", "");
input = input.replace("]", "");
input = input.replace("\"", "");
String[] parts = input.split(",");
I make a number of assumptions here:
Assume no spaces before and after the delimiting [, ], ,
Assume no , and " character in the Strings you want to extract
input.substring(1, input.length() - 1).replaceAll("\\\"", "").split(",");
Or if you don't want to mess with regular expression (replaceAll function works with regular expression), then you can use replace method:
input.substring(1, input.length() - 1).replace("\"", "").split(",");
Due to the assumptions above, this answer is very brittle. Consider using JSON parser if the data is really JSON.
String str = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
String strArry[] = null;
if(str.trim().length() > 0){
str = str.substring(1 , str.length()-1).replaceAll("\\\"", "");
strArry = str.split(",");
}
If s is the input string, it can just be as simple as
String[] idArray = s.replaceAll("[\\[\\]\"]", "").split(",");
it would be more secure (because ',' may be a decimal separator) to split with ("\",\""), and not remove trailing " in replaceAll, here subtring do not parse all the string :
final String str = "[\"4fd5f684815345\",\"4fd6ef3e60a676854651\",\"4fd83c33c19164512153\"]";
final String strArray[] = str.substring(2, str.length() - 2).split("\",\"");
final ArrayList<String> al = new ArrayList<String>();
for (final String string : strArray) {
al.add(string);
System.out.println(string);
}
System.out.println(al);
for (final String string : strArray) {
System.out.println(string);
}
Output :
4fd5f684815345
4fd6ef3e60a676854651
4fd83c33c19164512153
[4fd5f684815345, 4fd6ef3e60a676854651, 4fd83c33c19164512153]

Categories

Resources