I've made a class in Java to create an object and one of my static methods converts some JSON to the object (I have a JavaScript version so it makes for easy transference).
A sample bit of the JSON is:
{"header": ["H1","H2","H3"], "cells": [["R1C1","R1C2","R1C3"],["Row 2, Column 1","Row 2, C2","R2 - C2"]]}
In my method, I'm not using any JSON package because as far as I know, it would require me having to download one, so I've been using RegEx to extract the data.
Method:
public static Table jsonToTable(String json) {
Pattern h = Pattern.compile("\"header\": \[((?:\" *[^\"]+ *\",?)+)]");
Pattern r = Pattern.compile("\"cells\": \[((\[(?:(?:\" *[^\"]+ *\",?)+)],?)+)]");
Matcher hm = h.matcher(json);
Matcher rm = r.matcher(json);
ArrayList<String> header = new ArrayList(Arrays.asList(hm.group(0).split(",")));
String[] _rows = rm.group(0).split(",");
ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>();
for (String row : _rows) {
row = row.replace("[","");
row = row.replace("]","");
rows.add(new ArrayList(Arrays.asList(row.split(","))));
}
Table t = new Table(header);
for (ArrayList<String> row : rows) {
t.addRow(row);
}
return t;
}
With this method, I get a Runtime error whenever I use it. I get no description at all so I'm not 100% certain on what is causing the errors. I am just assuming the groups.
With the patterns however, how I have written them above, the opening [ braces have been escaped though ideone.com compiler doesn't like that so it's possible that's the problem.
Is anyone able to tell me what is causing the Runtime error? I've tried everything I can think of.
Aucun commentaire:
Enregistrer un commentaire