【问题标题】:Cast my class to JSONObject将我的课程转换为 JSONObject
【发布时间】:2014-05-29 11:37:22
【问题描述】:

我有一个我的类“Points”的对象数组,我想把它们放在一个 JSONArray 上,之前转换为 JSONObject,但是我有一个问题我无法解决,我不能把我的点[]在 JSONObject 上,我不知道该怎么做。我把代码解释得更好。

主要代码:

JSONArray jsPoints = new JSONArray();
for(int i = 0; i < points.length; i++)
{
    JSONObject js = new JSONObject(points[i]);
    jsPoints.put(js);
}

点类:

public class Point {

String _id; 
String _comment; 
String _calification; 
String _coords;
int _X;
int _Y;

public Point(String id, String comment, String calification, String coords, int x, int y)
{
    _id = id; 
    _comment = comment; 
    _calification = calification; 
    _coords = coords;
    _X = x;
    _Y = y;     
}
}

将价值观引入我的班级:

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,很棒的库,正是你正在寻找的东西

标签: java android json class


【解决方案1】:

试试GSON。这样做:

Gson gson = new Gson(); 
final MyClass myClass = gson.fromJson(jsonString, MyClass.class);

希望这会有所帮助.. :)

【讨论】:

    【解决方案2】:

    您不能直接将JSONArray 转换为Points

    您可以执行以下操作

    1. 以字符串形式获取 json
    2. 使用jackson(ObjectMapper)将json反序列化为Point

    【讨论】:

      【解决方案3】:

      在您的代码中

      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();
          }
      
      }
      

      【讨论】:

        【解决方案4】:

        您可以使用gson这样做

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-06-05
          • 2014-04-23
          • 2014-02-27
          • 1970-01-01
          • 1970-01-01
          • 2015-12-08
          • 1970-01-01
          相关资源
          最近更新 更多