Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (498)
Games in Android Showcase (115)
games submitted by our members
Games in WIP (562)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  json  (Read 3500 times)
0 Members and 1 Guest are viewing this topic.
Offline trollwarrior1
« Posted 2014-05-18 11:50:43 »

Hi, today I made a json parser or something like that.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
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:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
{
   "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]"
Offline gimbal

JGO Knight


Medals: 25



« Reply #1 - Posted 2014-05-22 09:53:19 »

Yeah I used to think making all the low-level stuff myself was fun too. Then its really "yours", right?

Eventually you'll change your mind and you'll focus on the high level stuff and gladly reuse tools, frameworks and APIs for the low level bits and bops. That way you actually get things done in stead of having to waste your time not only re-inventing the wheel but also maintaining it.
Offline trollwarrior1
« Reply #2 - Posted 2014-05-22 20:03:30 »

I kinda got a programmer job now.. The problem is that so far in 3 weeks all I have done is look at the code their and do literally no real programming or building something..

So I thought I need some exercise in order not to lose my skills. I figured making a UI system would be fun, so I made a json loader too. It was great exercise Tongue
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline opiop65

JGO Kernel


Medals: 154
Projects: 7
Exp: 3 years


JumpButton Studios


« Reply #3 - Posted 2014-05-22 20:50:52 »

You got a programming job after only 1 year of experience?

Offline trollwarrior1
« Reply #4 - Posted 2014-05-23 05:00:11 »

Its a job for a minimum wage, since I have never worked with other people before, mainly didn't use things like Git, Arcanist and didn't do any C++ programming.

Basically my wage will increase as I learn these things and become more productive.

I got hired, because they said I have a lot of potential. My Galaga game was actually a demo game for that job I had to make Cheesy

EDIT--
Ow, did I mention? I quit high school after finishing 10/12 years.
Offline DrZoidberg

Senior Member


Medals: 15



« Reply #5 - Posted 2014-05-23 14:53:21 »

Here is another JSON parser. It's a recursive descent parser and should be able to handle all standard json code.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
import java.util.*;
import java.io.*;

class JSON {
    static LinkedList<Object> tokenize(Scanner in) {
        LinkedList<Object> list = new LinkedList<>();
        while(true) {
            in.skip("\\s*");
            String token = in.findWithinHorizon(",|:|\\[|\\]|\\{|\\}|\".*?\"|'.*?'|true|false|null|\\d*\\.\\d*|\\d+", 0);
            if(token == null) {
                if(in.hasNext()) throw new RuntimeException();
                else return list;
            }
            char c = token.charAt(0);
            if(c == '"' && token.endsWith("\"") || c == '\'' && token.endsWith("'")) list.add(token.substring(1, token.length()-1));
            else if(c >= '
0' && c <= '9' || c == '.' ) list.add(Double.valueOf(token));
            else if(token.equalsIgnoreCase("true") || token.equalsIgnoreCase("false")) list.add(Boolean.valueOf(token));
            else if(token.equalsIgnoreCase("null")) list.add(null);
            else list.add(token);
        }
    }
   
    static Object parseValue(LinkedList<Object> tokens) {
        Object elem = tokens.pop();
        if(elem.equals("{")) return parseJSON(tokens);
        else if(elem.equals("[")) return parseArray(tokens);
        else return elem;
    }
   
    static List<Object> parseArray(LinkedList<Object> tokens) {
        ArrayList<Object> list = new ArrayList<>();
        if(tokens.peek().equals("]")) {tokens.pop(); return list;}
        while(true) {
            list.add(parseValue(tokens));
            Object elem = tokens.pop();
            if(elem.equals("]")) return list;
            else if(!elem.equals(",")) throw new RuntimeException();
        }
    }
   
    static Map<String, Object> parseJSON(LinkedList<Object> tokens) {
        HashMap<String, Object> map = new HashMap<>();
        if(tokens.peek().equals("}")) {tokens.pop(); return map;}
        while(true) {
            String key = (String)tokens.pop();
            if(!tokens.pop().equals(":")) throw new RuntimeException();
            Object value = parseValue(tokens);
            map.put(key, value);
            Object elem = tokens.pop();
            if(elem.equals("}")) return map;
            else if(!elem.equals(",")) throw new RuntimeException();
        }
    }
   
    static Map<String, Object> parseJSON(Scanner in) {
        LinkedList<Object> tokens = tokenize(in);
        if(!tokens.pop().equals("{")) throw new RuntimeException();
        return parseJSON(tokens);
    }
   
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(new File("test.json"));
        Map<String, Object> map = parseJSON(in);
        in.close();
        System.out.println(map);
       
    }
}
Online SilverTiger

Junior Member


Medals: 4
Exp: 2 years


がんばってください!


« Reply #6 - Posted 2014-05-23 14:59:52 »

Now that you have a JSON Parser you could expand it to a YAML (v1.2) Parser Grin

And +1 for the recursive descent parser Smiley
Pages: [1]
  ignore  |  Print  
 
 

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

BurntPizza (21 views)
2014-09-21 02:42:18

BurntPizza (15 views)
2014-09-21 01:30:30

moogie (17 views)
2014-09-21 00:26:15

UprightPath (25 views)
2014-09-20 20:14:06

BurntPizza (27 views)
2014-09-19 03:14:18

Dwinin (42 views)
2014-09-12 09:08:26

Norakomi (73 views)
2014-09-10 13:57:51

TehJavaDev (97 views)
2014-09-10 06:39:09

Tekkerue (49 views)
2014-09-09 02:24:56

mitcheeb (70 views)
2014-09-08 06:06:29
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!