Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将我的类强制转换为JSONObject_Java_Android_Json_Class - Fatal编程技术网

Java 将我的类强制转换为JSONObject

Java 将我的类强制转换为JSONObject,java,android,json,class,Java,Android,Json,Class,我有一个类点的对象数组,我想把它们放在一个JSONArray上,预先转换到JSONObject,但是我有一个问题我不能解决,我不能把我的点[]放在JSONObject上,我不知道怎么做。我用代码来更好地解释它 主要代码: JSONArray jsPoints = new JSONArray(); for(int i = 0; i < points.length; i++) { JSONObject js = new JSONObject(points[i]); jsPoin

我有一个类点的对象数组,我想把它们放在一个JSONArray上,预先转换到JSONObject,但是我有一个问题我不能解决,我不能把我的点[]放在JSONObject上,我不知道怎么做。我用代码来更好地解释它

主要代码:

JSONArray jsPoints = new JSONArray();
for(int i = 0; i < points.length; i++)
{
    JSONObject js = new JSONObject(points[i]);
    jsPoints.put(js);
}
将价值观引入我的课堂:

private void createPoints()
{
    points = new Point[drawedInterestPoints.size() / 2]; 
    int j = 0;
    for(int i = 0; i < drawedInterestPoints.size() - 1; i++)
    {
        if(i % 2 == 0)
        {
            points[j] = new Point(pointType.get(i),comments.get(i),calification.get(i),GPScoords.get(i),drawedInterestPoints.get(i),drawedInterestPoints.get(i + 1));
            j++;
        }
    }
}
任何人都可以告诉我,要将我的每个点[]放入JSONObject,然后放入JSONArray,我必须做什么?谢谢

试试GSON。这样做:

Gson gson = new Gson(); 
final MyClass myClass = gson.fromJson(jsonString, MyClass.class);
希望这有助于

您不能直接将JSONArray投射到点

你能做的事情如下

获取json作为字符串 使用jacksonObjectMapper将json反序列化为点 在代码中

JSONObject js = new JSONObject(points[i]);
毫无意义;您应该将points[]的每一项作为标记放在jsObject中,然后将其插入JsonArray中

试试这个:

public void jsonAsStr() {

    JSONObject mJsonObj = new JSONObject();

    try {
        mJsonObj.put("tag1", true);
        mJsonObj.put("tag2", 120);
        mJsonObj.put("tag3", "Demo");

        JSONArray jsPoints = new JSONArray();
        jsPoints.put(mJsonObj);

    } catch (JSONException e) {
        e.printStackTrace();
    }

}

您可以使用


看看gson,这是一个很好的库,正是你想要的
public void jsonAsStr() {

    JSONObject mJsonObj = new JSONObject();

    try {
        mJsonObj.put("tag1", true);
        mJsonObj.put("tag2", 120);
        mJsonObj.put("tag3", "Demo");

        JSONArray jsPoints = new JSONArray();
        jsPoints.put(mJsonObj);

    } catch (JSONException e) {
        e.printStackTrace();
    }

}
Gson gson = new Gson();
Point point = new Point("", "", "", "", 1, 2);
String json = gson.toJson(point);