如何以json对象或json数组的形式向服务器发送值

时间:2018-05-23 06:54:38

标签: android json gson

实际上,我想以json的形式将用户电话的联系人发送到服务器。我读到的某个地方,它可以通过GSON库完成,但我无法获得确切的代码。电话号码和联系人姓名是字符串形式。我曾经尝试过两门课。

一个是主类,我在其中获取联系人

public class Access_contacts extends AppCompatActivity {


    ArrayList<Contact_Pojo> arrayList;
    private static final int PERMISSION_REQUEST_CONTACT =123 ;
    private static final int PICK_CONTACT =147 ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_access_contacts);
        arrayList= new ArrayList<Contact_Pojo>();

        askForContactPermission();

        Gson gson = new Gson();
        Type type = new TypeToken<List<Contact_Pojo>>() {}.getType();
        String json = gson.toJson(arrayList, type);

        ArrayList<Contact_Pojo> fromJson = gson.fromJson(json, type);

        for (Contact_Pojo task : fromJson) {
            System.out.println(task);
        }



    }

    private void gettingPhoneContacts() {
        ContentResolver cr = getApplicationContext().getContentResolver();
        // Read Contacts
        Cursor c = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,     new String[] { ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,       ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.RawContacts.ACCOUNT_TYPE },     ContactsContract.RawContacts.ACCOUNT_TYPE + " <> 'google' ",
                null, null);
        if (c.getCount() <= 0) {    Toast.makeText(getApplicationContext(), "No Phone Contact Found..!",
                Toast.LENGTH_SHORT).show();   }
                else {
            while (c.moveToNext()) {
                String Phone_number = c       .getString(c         .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));          //Phone number
            String name = c       .getString(c         .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));


                    arrayList.add(new Contact_Pojo(name,Phone_number));


                Log.d("contactsss",Phone_number+ " "+name);
            //Name of contact
        }
        for(int i=0;i<arrayList.size();i++)
        {
        Log.d("jopo",""+arrayList.get(i));
        }

    }}

    private void askForContactPermission() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(Access_contacts.this,Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {

                // Should we show an explanation?
                if (ActivityCompat.shouldShowRequestPermissionRationale(Access_contacts.this,
                        Manifest.permission.READ_CONTACTS)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Access_contacts.this);
                    builder.setTitle("Contacts access needed");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setMessage("please confirm Contacts access");//TODO put real question
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @TargetApi(Build.VERSION_CODES.M)
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            requestPermissions(
                                    new String[]
                                            {Manifest.permission.READ_CONTACTS}
                                    , PERMISSION_REQUEST_CONTACT);
                        }
                    });
                    builder.show();
                    // Show an expanation to the user *asynchronously* -- don't block
                    // this thread waiting for the user's response! After the user
                    // sees the explanation, try again to request the permission.

                } else {

                    // No explanation needed, we can request the permission.

                    ActivityCompat.requestPermissions(Access_contacts.this,
                            new String[]{Manifest.permission.READ_CONTACTS},
                            PERMISSION_REQUEST_CONTACT);

                    // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                    // app-defined int constant. The callback method gets the
                    // result of the request.
                }
            }else{
                getContact();
            }
        }
        else{
            getContact();
        }
    }

    private void getContact() {
        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(intent, PICK_CONTACT);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CONTACT: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    gettingPhoneContacts();
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {
                    Toast.makeText(this, "No Permission for Contacts", Toast.LENGTH_SHORT).show();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
}

其他是POJO类,如下:

public class Contact_Pojo {


    @Override
    public String toString() {
        return "Contact_Pojo [name=" + name + ", number=" + number + "  ]";
    }


    public Contact_Pojo(String name, String number) {
        this.name = name;
        this.number = number;

    }

    String name,number;;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }


}

2 个答案:

答案 0 :(得分:1)

这是解决方案。你必须决定&#34;你需要什么?&#34; JSONOject或JSONArray。 在顶部声明。

JSONObject mainObject = new JSONObject();
JSONArray jsonBody;

现在在OnCreate中

              jsonBody = new JSONArray();
                 try {
                    JSONObject object_1 = new JSONObject();
                    object_1.put("KEY_VALUE", KEY_PAIR);
                    object_1.put("KEY_VALUE", KEY_PAIR);
                    object_1.put("KEY_VALUE", KEY_PAIR);
                    object_1.put("KEY_VALUE", KEY_PAIR);
                    object_1.put("KEY_VALUE", KEY_PAIR_id);
                    jsonBody.put(0, object_1);
                    mainObject.put("data", jsonBody);
                  String data = mainObject.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }

在KEY_PAIR中添加键代替KEY_VALUE及其值。

如果需要发送JSONArray传递jsonBody,如果需要JSONObject则使用mainObject。

答案 1 :(得分:0)

我认为您应该使用JSONObject和JSONArray,如:

JSONArray array = new JSONArray("Catalo");

        JSONObject contact = new JSONObject();
        contact.put("key", "value");
        contact.put("key", "value");
        ...
        array.put(contact);