代码之家  ›  专栏  ›  技术社区  ›  Tapesh Gupta

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

  •  0
  • Tapesh Gupta  · 技术社区  · 6 年前

    实际上,我想以JSON的形式将用户电话的联系人发送到服务器。在我读到的某个地方,它可以通过GSON图书馆完成,但我无法得到确切的代码。电话号码和联系人姓名是以字符串的形式出现的。我试过上2节课。

    一个是主班,我在那里接联系人

    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 回复  |  直到 6 年前
        1
  •  0
  •   SonVi    6 年前

    我认为您应该使用jsonObject和jsonArray,比如:

    JSONArray array = new JSONArray("Catalo");
    
            JSONObject contact = new JSONObject();
            contact.put("key", "value");
            contact.put("key", "value");
            ...
            array.put(contact);
    
        2
  •  1
  •   halfer Rahul Baradia    6 年前

    这是解决方案。你必须决定“你需要什么?”jsonObject或jsonArray。 在顶部申报。

    JSONObject mainObject = new JSONObject();
    JSONArray jsonBody;
    

    现在在里面创建

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

    添加您的密钥以代替密钥对中的密钥值和它们的值。

    如果需要发送jsonarray,请传递jsonbody;如果需要jsonobject,请使用mainobject。