Skip to content

Commit d9e2fc8

Browse files
committed
read the yaml file
1 parent 13cedb1 commit d9e2fc8

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
package ood.design;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import java.util.*;
6+
7+
public class ConvertJSONtoMap {
8+
9+
private Map<String, Object> map;
10+
11+
@Test
12+
public void parse(){
13+
String test = "K1:V1\n"+
14+
"K2:V2\n"+
15+
"K3:\n"+
16+
" K31:V31\n"+
17+
" K32:\n"+
18+
" K321:V321\n"+
19+
" K322:V322\n"+
20+
" K333:V333\n"+
21+
"K4:\n"+
22+
" K41:V41\n"+
23+
" K42:V42";
24+
25+
myImpl(test);
26+
27+
}
28+
29+
void jsonToMap(String input){
30+
Map<String, Object> root = new HashMap<>();
31+
Stack<LevelNode> stack = new Stack<>();
32+
stack.push(new LevelNode(0, root));
33+
34+
for(String line : input.split("\n")) {
35+
int level = line.lastIndexOf(" ") + 2;
36+
while(stack.peek().level >= level){
37+
stack.pop();
38+
}
39+
var parts = line.trim().split(":");
40+
if(parts.length < 2){
41+
// new parent
42+
var newParent = new HashMap<String, Object>();
43+
stack.peek().map.put(parts[0], newParent);
44+
stack.push(new LevelNode(level, newParent));
45+
} else{
46+
stack.peek().map.put(parts[0], parts[1]);
47+
}
48+
}
49+
50+
this.map = root;
51+
System.out.println(map);
52+
}
53+
54+
private void myImpl(String input){
55+
Map<String,Object> root = new HashMap<>();
56+
Stack<LevelNode> stack = new Stack<>();
57+
stack.push(new LevelNode(0,root));
58+
59+
for(String line : input.split("\n")){
60+
int level = line.lastIndexOf(" ") + 2;
61+
62+
while(stack.peek().level >= level)
63+
stack.pop();
64+
65+
String[] lines = line.split(":");
66+
67+
if(lines.length < 2){
68+
var child = new HashMap<String,Object>();
69+
stack.peek().map.put(lines[0].strip(),child);
70+
stack.push(new LevelNode(level,child));
71+
} else stack.peek().map.put(lines[0].strip(),lines[1]);
72+
}
73+
System.out.println(root);
74+
}
75+
76+
public Object get(String key){
77+
Object value = this.map.get(key);
78+
if(value instanceof Map){
79+
return value;
80+
} else{
81+
return null;
82+
}
83+
}
84+
85+
private static class LevelNode {
86+
87+
int level;
88+
Map<String, Object> map;
89+
90+
public LevelNode(int level, Map<String, Object> map){
91+
this.level = level;
92+
this.map = map;
93+
}
94+
}
95+
}

0 commit comments

Comments
 (0)