Guest User

Untitled

a guest
Mar 19th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. public class Simplejson {
  5.  
  6. private String body;
  7. private int numItems;
  8. private List<String> keys = new ArrayList<String>();
  9. private List<String> values = new ArrayList<String>();
  10.  
  11. public Simplejson() {
  12. body = "{}";
  13. }
  14.  
  15. private void rebuild() {
  16.  
  17. this.body = new String ("{");
  18. for(int i = 0; i < numItems; i++) {
  19. String key = "\"" + this.keys.get(i) + "\":";
  20. String value = "\"" + this.values.get(i) + "\"";
  21. String line = key + value;
  22. if(i < numItems - 1) {
  23. line += ",";
  24. }
  25. this.body += line;
  26. }
  27. this.body += "}";
  28. }
  29.  
  30. public void add(String newKey, String newValue) {
  31. if(!this.keys.contains(newKey)) {
  32. this.keys.add(newKey);
  33. this.values.add(newValue);
  34. this.numItems++;
  35. }
  36. else {
  37. this.update(newKey, newValue);
  38. }
  39. }
  40.  
  41. public void remove(String key) {
  42. if(this.keys.contains(key)) {
  43. int index = this.keys.indexOf(key);
  44. this.keys.remove(index);
  45. this.values.remove(index);
  46. this.numItems--;
  47. }
  48. }
  49.  
  50. public void update(String key, String newValue) {
  51. if(this.keys.contains(key)) {
  52. int index = this.keys.indexOf(key);
  53. this.values.set(index, newValue);
  54. }
  55. else {
  56. this.add(key, newValue);
  57. }
  58. }
  59.  
  60. public int getLength() {
  61. return this.numItems;
  62. }
  63.  
  64. public String build() {
  65. this.rebuild();
  66. return this.body;
  67. }
  68. }
Add Comment
Please, Sign In to add comment