将字符串转换为json对象会产生错误

时间:2016-09-16 05:37:31

标签: java arrays json

我必须将json数组发送到Web服务器。我从数组列表创建了json数组。我有一个帮助程序类,它将json对象发送到服务器。

所以我想将json数组转换为json对象。

我试着这样做:

异步任务:

public class SendMultipleInvitesAsyncTask extends AsyncTask<String, Void, JSONObject> {

    private Context context;
    JSONArray array = new JSONArray();

    public SendMultipleInvitesAsyncTask(Context context)
    {

        this.context = context;

    }

        @Override
        protected JSONObject doInBackground(String... params) {
            try {
                String api = context.getResources().getString(R.string.server_url) + "contactsapi/sendMultipleInvite.php";

                JSONObject obj = new JSONObject(params[0]);

                ServerRequest request = new ServerRequest(api,obj);
                return request.sendRequest();

            } catch(JSONException je) {
                return Excpetion2JSON.getJSON(je);
            }
        }

活动:

public class SendMultipleInvites扩展了AppCompatActivity {

private ArrayList<Invitation> invitationArrayList;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_multiple_invites);

  invitationArrayList = new ArrayList<>();

    Invitation invitation = new Invitation("3","17/02/2016","55165122","1","user10");

    invitationArrayList.add(invitation);

    invitation = new Invitation("3","17/02/2016","282751221","1","user10");

    invitationArrayList.add(invitation);

   // JSONArray jsArray = new JSONArray(invitationArrayList);


    Gson gson=new Gson();
    String toServer=gson.toJson(invitationArrayList);



    new SendMultipleInvitesAsyncTask(SendMultipleInvites.this).execute(toServer);

但这给了我一个错误,即json对象无法转换为json数组。

我想像这样发送json数组的输入:

{
"invitations": [
    {

   "sender_id" : 3,
    "date" : "12/08/2016",
    "invitee_no" : "196756456",
    "status" : "1",
    "user_name" : "user10"

    },
    {

   "sender_id" : 3,
    "date" : "12/08/2016",
    "invitee_no" : "13633469",
    "status" : "1",
    "user_name" : "user9"

    }
  ]

}

我该怎么做?如何通过异步任务传递它。或者这里出了什么问题?请帮忙谢谢..

1 个答案:

答案 0 :(得分:1)

invitationArrayList是你的ArrayList所以jo得到一个JSON数组。如果你想将这个数组包装在一个JSON对象中,你也必须在java中使用它。

例如:

String toServer = gson.toJson(
    Collections.singletonMap("invitations", invitationArrayList)
);

(假设gson.toJson按预期工作。我不是 gson 专家,因为我主要使用jackson ...)

Collections.singletonMap的JavaDoc:https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#singletonMap(K,%20V)