Parsing Multiple JSON Arrays in Java/Android - java

If you pass multiple JSON arrays into Java (in a single stream) that looks like this:
[ <-----json objects---->] [ <-----json objects---->] [ <-----json objects---->]
How do you parse in Java? And is there a way to do it without rewriting the JSON data into a single array?
Essentialy, I want to get to a point where I can do this after the parsing.
item = json.getString("item");
total = json.getString("total");
items.add(item);
totals.add(total);
A key note is that the first array is items, the second array is totals. The first json object in items corresponds to the first in totals.

I would say that you need first of all transform this content in a valid JSON, maybe you could first replace ]\s*[ by ],[ and add [ at the beggining and ] at the end. This would be a valid JSON and could be parsed as an JSONArray that contains many JSONArrays.
Something like:
String receivedJSON = "[{},{}] [{},{}] [{}]";
String normalized = "[" + receivedJSON.replaceAll("\\]\\s*\\[", "],[") + "]";
new JSONArray(normalized);

Related

Scala : Select the Jackson JsonNode keys using Regex filter in a json

I have sample jsonNode data - Inputstr =
{
"a.b.c.d.e":"123",
"a[0].b.c.d[0].e":"123",
"a[0].b.c.d[1].e":"123",
"a[1].b.c.d[0].e":"123",
"a[1].b.c.d[1].e":"123",
"d.e.f"="789",
"x.y.z"="789"
}
I want to extract the keys having data in format a[0-9*].b[0-9*].c[0-9*].d[0-9*].e[0-9*].
Basically, the output should return me, 0 or more occurrences
[ a.b.c.d.e , a[0].b.c.d[0].e, a[0].b.c.d[1].e, a[1].b.c.d[0].e, a[1].b.c.d[1].e ].
So, what i did was
val json = ObjectMapper.readTree(Inputstr)
val itr = json.fieldNames
Now on this iterator of keys i want to create a generic regex which returns me the above output.
I tried but not working
val regex = """a\[[0-9\]]*.b\[[0-9\]]*.c\[[0-9\]]*.d\[[0-9\]]*.e\[[0-9\]]*""".r
while(itr.hasNext())
{
val str= itr.next()
regex.findAllIn(str)
}
I am stuck in creating the regex basically which can take [0-9]*, it should check for both the braces [ ] as well as presence of a digit from 0 to 9 inside the braces. Even if none exists, it should return me a.b.c.d.e as well.
I hope it makes sense.
Please let me know if any questions.
a(?:\[\d])?\.b(?:\[\d])?\.c(?:\[\d])?\.d(?:\[\d])?\.e(?:\[\d])?
Should do the job, I included the [0] part inside of a non matching group that can be optional using ?

How to get string data of one column as an array data from data base

In an app I have used 7 checkboxes to get the days name from user and I am storing those name in an array based on selected checkboxes and then converting them to String data and store in database now I want to get the data back as an array only.
for eg:
days={"Mon","Tue","Wed","Sat"}
And now the database column has this value as: [Mon,Tue,Wed,Sat] which is stored as a String.
I can get this string back but how to convert it back to array so that i can compare the array data with current day like if today is Mon so i can find out which column has Mon.
Please help me out as I don't know what to search any related link or post or any suggestions how to achieve this. Thanks.
You can do it like this. Though, your values should not have "," in them.
String[] strs = new String[] { "Foo", "Bar", "Baz" };
String joined = Arrays.toString( strs );
String joinedMinusBrackets = joined.substring( 1, joined.length() - 1);
// String.split()
String[] resplit = joinedMinusBrackets.split( ", ");
you can refer this post
or you convert the resultset into an array using getArray() method, javadoc

Java 8 find and replace matching string(s)

I am trying to find a string from messages.properties in an errorMessage and if the errorMessage has the string I need to replace it with corresponding value
I have messages.properties as below
inv_date=INVOICE DATE
inv_id=INVOICE NUMBER
cl_id=CLIENT ID
lf_matter_id=LAW FIRM MATTER ID
inv_total_net_due=INVOICE TOTAL
(inv_start_date|invoice start date)=BILLING START DATE
(inv_end_date|invoice end date)=BILLING END DATE
inv_desc=INVOICE DESCRIPTION
units=LINE ITEM NUMBER OF UNITS
discount_amount=LINE ITEM ADJUSTMENT AMOUNT
total_amount=LINE ITEM TOTAL
(charge_date|charge date)= LINE ITEM DATE
acca_task=LINE ITEM TASK CODE
acca_expense=LINE ITEM EXPENSE CODE
acca_activity= LINE ITEM ACTIVITY CODE
(tk_id|time keeper id)=TIMEKEEPER ID
charge_desc=LINE ITEM DESCRIPTION
lf_id=LAW FIRM ID
(BaseRate|Rate|tk_rate)=LINE ITEM UNIT COST
tk_level=TIMEKEEPER CLASSIFICATION
cl_matter_id=CLIENT MATTER ID
My errorMesage can have any of the (left side)string and I need to replace it with right side string value
Below are couple of sample error messages
String errorMesage1 = "Line 3 : Could not parse inv_date value"
String errorMesage2 = "Line : 1 BaseRate is a required field"
below is my method which conversts the error message
public static String toUserFriendlyErrorMessage(String message) {
ResourceBundle rb = ResourceBundle.getBundle("messages");
for(String key : rb.keySet()){
String header = rb.getString(key);
if(message.contains(key)) {
return message.replaceAll(key, rb.getString(key));
}
}
return message;
}
Below is the expected output:
for errorMessage1 it works fine
System.out.println(toUserFriendlyErrorMessage(errorMessage1)); ==> Line 3 : Could not parse INVOICE DATE value
But for errorMessage2 its not working. It doesnt replace BaseRate with LINE ITEM UNIT COST
System.out.println(toUserFriendlyErrorMessage(errorMessage2)); ==> Line : 1 BaseRate is a required field
Is there a way to find the occurance of multiple strings and replace it with its corresponding value?
For example: Find (BaseRate|Rate|tk_rate) and replace the string with LINE ITEM UNIT COST
Also am wondering can this method simplified further in java 8?
I think you should reconsider your design and use individual keys for the several "aliases" - or probably even better: No aliases at all and just one key per replacement. The problem is that the keys in those properties files are not supposed to contain spaces -- parantheses or not -- so the files are not parsed correctly. If you print the keys, you will see that they are truncated at the first space, e.g. (inv_start_date|invoice start date) becomes (inv_start_date|invoice.
Of course, this also means that, even if you split those "aliases" into separate keys, you can not have keys like invoice start date, as it still contains spaces and will not be parsed correctly.
You could just put those replacements into a regualr Map in your Java source code:
static Map<String, String> replacements = new HashMap<>();
static {
replacements.put("inv_date", "INVOICE DATE");
replacements.put("(BaseRate|Rate|tk_rate)", "LINE ITEM UNIT COST");
// ... more stuff ...
}
Or parse the file manually, splitting the strings at = and putting them into a Map.
And since keys like (BaseRate|Rate|tk_rate) are in fact valid regular expressions, you can just use replaceAll to replace them in all their variants. If they are not contained in the string, replaceAll will just do nothing, so the contains check is not really necessary.
public static String toUserFriendlyErrorMessage(String message) {
for (String key : replacements.keySet()) {
message = message.replaceAll(key, replacements.get(key));
}
return message;
}
Example output:
Line 3 : Could not parse INVOICE DATE value
Line : 1 LINE ITEM UNIT COST is a required field
Or, if you want to use some "Java 8 magic", you could use reduce, but personally, I think the loop is more readable.
return replacements.keySet().stream()
.reduce(message, (s, k) -> s.replaceAll(k, replacements.get(k)))
.toString();

Cut String in parts

I'm getting from JSON string like this:
{
"name":"Google"
"items": "item1,item2,item3,item4"
}
So I want to create array String[] items and populate it with items from this string. I need somehow to cut this string in parts. Also I'm getting different number of items, not only 4, like in example.
How can I do this....?
String[] items = incomingString.split(",");
Look at String.split() you can pass in a char that will split up your string and return an array
are you looking for the below line or I misunderstood your question ?
String[] result = yourString.split(",");

How to pull data from a txt file into a HTML table Java/JSP

I have a Text file (.txt) that contains data strings using comma separated values, i.e
jordan,hello,12th Feb 15:23, pending
I would like to then pull this data into a HTML table with the ",' separating each column. For example the headings of the table would be:
Name Question Date Status
Thus Jordan would go in the name column and hello under question etc.
Currently I have output the full string but I need the individual elements.
Any advice would be appreciated.
You need a parser to read csv file and create individual elements. You can either use String.split(...) or even better leverage CSV parsing libraries. Create a class Data and populate it with the parsed data (each row has a corresponding Data object). You should have a List<Data> after the entire file has been parsed which you can pass to the JSP page. JSP then iterates through the List and creates the table.
Assuming that you don't have a , in the data, simply call split(",") on each line and create a custom formatted HTML table, something like this (haven't tested):
out.println("<table>")
for (int i=0; i<lines.length; ++i) {
out.println("<tr>" )
String[] data = line[i].split(",");
for (String val : data) {
out.println("<td>" + val + "</td>")
}
out.println("</tr>" )
}
out.println("</table>")
You can use the String#Split method to convert your actual String to an array of Strings with all the values:
String s = "jordan,hello,12th Feb 15:23, pending"
String[] sArray = s.split(",");
for(String si : sArray) {
//you can print them in your output
}

Categories