我正在尝试从json文件中读取内容,以便通过处理创建视觉图像。到目前为止,我的代码是:
ldconfig
stoke []是一个浮点数组,它将控制笔触的颜色。 我解析的json文件是
public void generateShape(JSONObject file) {
//convert file to json object
JSONArray shapes = (JSONArray) file.get("shapes");
for (Object o : shapes) {
JSONObject json_shape = (JSONObject)o;
//getting shape id and function so we know which shapes to create
id = ((Number) json_shape.get("id")).intValue();
func = ((Number) json_shape.get("func")).intValue();
animate = ((Number) json_shape.get("animate")).intValue();
stroke_weight = ((Number) json_shape.get("stroke_weight")).floatValue();
JSONArray strokes = (JSONArray) json_shape.get("stroke");
Iterator<Float> iterator = strokes.iterator();
index = 0;
while(iterator.hasNext())
{
stroke[index] = ((Number)iterator.next()).floatValue();
index++;
}
我在一行中得到错误:
{
"shapes": [
{
"id":0,
"func":1,
"stroke":[143,50,200],
"stroke_weight": 70,
"animate": 1,
"jelly_func": 5,
"points":[268,330,400,333,74,210,90,300]
}
]
}
我正在使用json.simple库,而我所看到的所有解决方案都是针对org.json库的
我可以对笔触数组中的值进行硬编码,但我想尝试迭代。有任何提示/指导吗?
完整堆栈跟踪为
stroke[index] = ((Number)iterator.next()).floatValue();
其中草图是:
java.lang.NullPointerException
at ImageLoader.generateShape(ImageLoader.java:35)
at Sketch.setup(Sketch.java:48)
at processing.core.PApplet.handleDraw(PApplet.java:2404)
at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1557)
at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:313)
eta:好的,因此删除导致异常的行,并检查是否甚至读取了我的json值,我可以在将它们打印到控制台时确认所解析的值是正确的。我现在需要将它们放在一个数组中
答案 0 :(得分:0)
我仍然认为您没有正确初始化数组...您可以尝试这段代码,看看它是否有效吗?
public void generateShape(JSONObject file) {
// convert file to json object
JSONArray shapes = (JSONArray) file.get("shapes");
for (Object o : shapes) {
JSONObject json_shape = (JSONObject) o;
// getting shape id and function so we know which shapes to create
int id = ((Number) json_shape.get("id")).intValue();
int func = ((Number) json_shape.get("func")).intValue();
int animate = ((Number) json_shape.get("animate")).intValue();
float stroke_weight = ((Number) json_shape.get("stroke_weight")).floatValue();
JSONArray strokes = (JSONArray) json_shape.get("stroke");
Iterator<Float> iterator = strokes.iterator();
int index = 0;
float[] stroke = new float[strokes.size()];
while (iterator.hasNext()) {
stroke[index] = ((Number) iterator.next()).floatValue();
index++;
}
}
}