Convert normal Java Array or ArrayList to Json Array in android

前端 未结 8 1327
栀梦
栀梦 2020-11-29 06:15

Is there any way to convert a normal Java array or ArrayList to a Json Array in Android to pass the JSON object to a webservice?

相关标签:
8条回答
  • 2020-11-29 06:41

    This is the correct syntax:

    String arlist1 [] = { "value1`", "value2", "value3" };
    JSONArray jsonArray1 = new JSONArray(arlist1);
    
    0 讨论(0)
  • 2020-11-29 06:47

    If you want or need to work with a Java array then you can always use the java.util.Arrays utility classes' static asList() method to convert your array to a List.

    Something along those lines should work.

    String mStringArray[] = { "String1", "String2" };
    
    JSONArray mJSONArray = new JSONArray(Arrays.asList(mStringArray));
    

    Beware that code is written offhand so consider it pseudo-code.

    0 讨论(0)
  • 2020-11-29 06:51

    Convert ArrayList to JsonArray : Like these [{"title":"value1"}, {"title":"value2"}]

    Example below :

    Model class having one param title and override toString method

    class Model(
        var title: String,
        var id: Int = -1
    ){
        
        override fun toString(): String {
            return "{\"title\":\"$title\"}"
        }
    }
    

    create List of model class and print toString

    var list: ArrayList<Model>()
    list.add("value1")
    list.add("value2")
    Log.d(TAG, list.toString())
    

    and Here is your output

    [{"title":"value1"}, {"title":"value2"}]
    
    0 讨论(0)
  • 2020-11-29 06:53

    you need external library

     json-lib-2.2.2-jdk15.jar
    
    List mybeanList = new ArrayList();
    mybeanList.add("S");
    mybeanList.add("b");
    
    JSONArray jsonA = JSONArray.fromObject(mybeanList);
    System.out.println(jsonA);
    

    Google Gson is the best library http://code.google.com/p/google-gson/

    0 讨论(0)
  • 2020-11-29 07:02
    ArrayList<String> list = new ArrayList<String>();
    list.add("blah");
    list.add("bleh");
    JSONArray jsArray = new JSONArray(list);
    

    This is only an example using a string arraylist

    0 讨论(0)
  • 2020-11-29 07:04

    For a simple java String Array you should try

    String arr_str [] = { "value1`", "value2", "value3" };
    
    JSONArray arr_strJson = new JSONArray(Arrays.asList(arr_str));
    System.out.println(arr_strJson.toString());
    

    If you have an Generic ArrayList of type String like ArrayList<String>. then you should try

     ArrayList<String> obj_list = new ArrayList<>();
        obj_list.add("value1");
        obj_list.add("value2");
        obj_list.add("value3");
      JSONArray arr_strJson = new JSONArray(obj_list));
      System.out.println(arr_strJson.toString());
    
    0 讨论(0)
提交回复
热议问题