Hi, today I made a json parser or something like that.
public class GJsonObject {
public String name = "GJsonObject";
public String value = "empty";
public GJsonObject parent = null;
private List<GJsonObject> children = new ArrayList<GJsonObject>();
public GJsonObject() {
}
public GJsonObject(String name, String value) {
this.name = name;
this.value = value;
}
public GJsonObject findNode(String node) {
if (name.equals(node)) return this;
for (GJsonObject child : children) {
GJsonObject jsonObject = child.findNode(node);
if (jsonObject != null) return jsonObject;
}
return null;
}
public void add(GJsonObject json) {
json.parent = this;
children.add(json);
}
public static GJsonObject parse(String strJson) {
StringReader reader = new StringReader(strJson);
GJsonObject lastNode = new GJsonObject();
try {
char ch = ' ';
boolean parsingString = false;
String string = "";
boolean readingData = false;
while (true) {
int integer = reader.read();
ch = (char) integer;
if (integer == -1) break;
if (!parsingString) {
// NOT parsing string
if (ch == '"') {
// start parsing string
parsingString = true;
}
if (ch == ':') {
// create new node and load data to it
GJsonObject newNode = new GJsonObject(string, "");
lastNode.add(newNode);
lastNode = newNode;
readingData = true;
string = "";
}
if (ch == '{') {
// not parsing data, parsing new nodes
readingData = false;
}
if (ch == ',') {
// go back to previous node
lastNode = lastNode.parent;
}
if (ch == '}') {
// go back 2 nodes.
lastNode = lastNode.parent;
if (lastNode.parent != null) {
lastNode = lastNode.parent;
} else {
// parent is null, done parsing the file
break;
}
}
} else {
// parsing string
if (ch == '"') {
// done parsing string
parsingString = false;
if (readingData) {
// was reading data, so store it to last node
readingData = false;
lastNode.value = string;
string = "";
}
} else {
// parse the string
string += ch;
}
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return lastNode;
}
}
Here you go.
Why did I make it? Because using already made ones is not fun. And this was very good practice… Improving programming skills is never a bad thing.
Here is some code you can test this bad boy on:
{
"Person": {
"Name": "Jon",
"Address": "Cool street 7",
"Family": {
"Mom": "Lila",
"Son": "Bran"
},
"phone": "888 8888"
}
}
EDIT----------
Hmmmmmmm I just realized I need to add support for things like : [4,0,1] instead of : “[4,0,1]”