-1

I have a json file which contains json array representing some shapes like that,

[{"Cordinates":  [272.0,81.0,200.0,100.0],
  "Type":"Ellipse2D",
  "Color":java.awt.Color[r=255,g=0,b=0]},
 {"Cordinates":[227.0,272.0,200.0,100.0],
  "Type":"Rectangle2D",
  "Color":java.awt.Color[r=255,g=0,b=0]}
]

the errors

Unexpected character (j) at position 67.

And here is my code to parse this

public List<ShapeItem> read() {     
    try {
        Object obj = parser.parse(new FileReader(filePath));
        JSONArray ja = (JSONArray)obj;          
        for (int j = 0; j < ja.size(); j++){
             JSONObject si = (JSONObject) ja.get(j);
             String type = (String) si.get("Type");             
             JSONArray cordinates = (JSONArray) si.get("Cordinates");
             Float x, y, width, height;
             x = (Float) cordinates.get(0);
             y = (Float) cordinates.get(1);
             width = (Float) cordinates.get(2);
             height = (Float) cordinates.get(3);
             if (type.equals("Ellipse2D")){
                s = new Ellipse2D.Float(x, y, width, height);
             }
             else if (type.equals("Rectangle2D")){
                s = new Rectangle2D.Float(x, y, width, height);
             }
             c = (Color) si.get("Color");
             shapeItem = new ShapeItem(s, c);
             shapes.add(shapeItem);
        }   
     }  
      return shapes;
  }

I want to read this file and create those shapes and return array of shapes but i got errors any help?

name
  • 25
  • 7

1 Answers1

6

A JSON object attribute that describes a single value should be a key-value pair where the value is one of the valid JSON attribute value types such as a string or a number.

However, your Color attribute does not have a value that can be turned into either of these.

Specifically:

"Color":java.awt.Color[r=255,g=0,b=0]

Is in no way valid JSON.

Try specifying your color like this instead:

"Color":"#ffff0000"
Michael Krause
  • 4,689
  • 1
  • 21
  • 25
  • 1
    @SotiriosDelimanolis: Very good point. I could have done a better job of clarifying the first time around. I've modified the answer to better accommodate the ability to specify a variety of different types for an attribute value. – Michael Krause Nov 06 '14 at 15:51
  • so how would i store color in json – name Nov 06 '14 at 15:52
  • 1
    You could represent it as a color string of the form "#aarrggbb" or an integer value encoding the argb you want. – Michael Krause Nov 06 '14 at 15:53