1

I am using something like this-

String Number1=to_1;
        String Number2=to_2;
        String[] arrayNumbers = new String[] {(char)34+Number1+(char)34,(char)34+Number2+(char)34};
        System.out.println(Arrays.toString(arrayNumbers));
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("to",Arrays.toString(arrayNumbers));
        jsonObj.put("type",type);
        jsonObj.put("callback",callbackUrl);
        JSONArray array = new JSONArray();
        JSONObject Array_item = new JSONObject();
        jsonObj.put(type, array);
        Array_item.put("caption",captionName);
        array.add(Array_item);

        System.out.println(jsonObj.toString());

Expected-

{
  "to":["91890xx", "91890xx"],
 "type": "document", "document" : {"caption" : "doc"},
"callback":"{{callback}}"
}

Actual- {"document":[{"caption":"hello"}],"callback":"{{callback}}","to":"[\"91890xxx\", \"91890xx\"]","type":"document"}

I don't know any more logic to remove the out double quotes of to number where as its considering that to a string where as both the numbers should be array format as mentioned in Expected.

1
  • Why don't you use just jsonObj.put("to",new JSONArray().put("").put(""))? Commented Mar 11, 2019 at 9:50

6 Answers 6

1

First, I show you the correct codes:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Test {
  /**
   * <pre>
   *  {
   *    "to":["91890xx", "91890xx"],
   *    "type": "document",
   *    "document" : {"caption" : "doc"},
   *    "callback":"{{callback}}"
   *  }
   * </pre>
   *
   * @param args
   * @throws JSONException
   */
   public static void main(String[] args) throws JSONException {
    String number1 = "91890";
    String number2 = "91890";
    String[] numbers = new String[]{number1, number2};

    JSONArray toNode = new JSONArray();
    for (String number : numbers) {
      toNode.put(number);
    }

    JSONObject jsonObj = new JSONObject();
    jsonObj.put("to", toNode);
    jsonObj.put("type", "document");
    jsonObj.put("document", new JSONObject().put("caption", "doc"));
    jsonObj.put("callback", "{{callback}}");

    System.out.println(jsonObj.toString());
  }
}

Result:

{"document":{"caption":"doc"},"callback":"{{callback}}","to":["91890","91890"],"type":"document"}

If you want create a josn array node, you show use JSONArray, and use JSONArray#put(*) method to add elements.

Put string into JSONArray or JSONObject, you don't need wrap the string with quote("). Besides, you should write \" instead of (char) 34 which is a little obscure in Java.


The following case is used to reply comments.

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.net.URI;
import java.net.URL;
import java.util.*;

public class Test1 {

  public static void main(String[] args) throws JSONException {
    Map<String, Object> map = new HashMap<>();
    map.put("key1", "value1");
    map.put("key2", new Date());
    map.put("key3", 1);
    map.put("key4", null);
    map.put("key5", Collections.singletonMap("key5-key1", "value"));
    map.put("key6", Arrays.asList(1, 2, 3, 4));
    map.put("key7", BigDecimal.TEN);
    map.put("key8", new String[]{"a", "b", "c"});
    map.put("key9", TestEnum.A);
    map.put("key10", new TestEnum[]{TestEnum.A, TestEnum.B, TestEnum.C});

    Object json = buildJsonObj(map);
    System.out.println(json);
  }

  private static Object buildJsonObj(Object source) throws JSONException {
    if (source == null) {
      return null;
    }
    if (isSimpleValueType(source.getClass())) {
      return source;
    }

    if (source instanceof Map) {
      Map<Object, Object> map = (Map<Object, Object>) source;
      JSONObject jsonObject = new JSONObject();
      for (Map.Entry<Object, Object> entry : map.entrySet()) {
        Object key = entry.getKey();
        if (!(key instanceof String)) {
          throw new IllegalArgumentException("key must be string.");
        }
        jsonObject.put((String) key, buildJsonObj(entry.getValue()));
      }
      return jsonObject;
    }
    if (source instanceof Iterable) {
      Iterable<Object> iterable = (Iterable<Object>) source;
      JSONArray jsonArray = new JSONArray();
      for (Object value : iterable) {
        jsonArray.put(buildJsonObj(value));
      }
      return jsonArray;
    }
    if (source.getClass().isArray()) {
      Object[] array = (Object[]) source;
      JSONArray jsonArray = new JSONArray();
      for (Object value : array) {
        jsonArray.put(buildJsonObj(value));
      }
      return jsonArray;
    }

    throw new IllegalArgumentException("Unsupported type: " + source + ".");
  }

  private static boolean isSimpleValueType(Class<?> clazz) {
    return (Enum.class.isAssignableFrom(clazz) ||
        CharSequence.class.isAssignableFrom(clazz) ||
        Number.class.isAssignableFrom(clazz) ||
        Date.class.isAssignableFrom(clazz) ||
        URI.class == clazz || URL.class == clazz ||
        Locale.class == clazz);
  }

  public enum TestEnum {
    A, B, C
  }
}

Result:

{"key1":"value1","key2":"Thu Mar 14 20:20:49 CST 2019","key5":{"key5-key1":"value"},"key6":[1,2,3,4],"key3":1,"key9":"A","key7":10,"key8":["a","b","c"],"key10":["A","B","C"]}
Sign up to request clarification or add additional context in comments.

4 Comments

I have question, What if I the same function needs to be used for one number also. Because this looks like hard coded.
You can define a function to do that. The function's param can be map and list/array. And you use JSONObject to process map, JSONArray to process list/array. Recursive algorithm should be used in those functions.
Will you able to explain with an example?
Man you are genius. Thanks
1

Replace line

jsonObj.put("to",Arrays.toString(arrayNumbers));

to

jsonObj.put("to", Arrays.asList(arrayNumbers));

Comments

0

Your value is String of 'to',so can you please convert string to json after that you can convert json to array.

Comments

0

Replace

jsonObj.put("to",Arrays.toString(arrayNumbers));

With

jsonObj.put("to",arrayNumbers);

Comments

0
let a = {"document":[{"caption":"hello"}],"callback":"{{callback}}","to":"[\"91890xxx\", \"91890xx\"]","type":"document"};

    a = JSON.parse(JSON.stringify(a));

    let b = JSON.parse(a.to);

    a.to = b;

    console.log(a);

Comments

0

This is the exact structure of you required json.

 {
        "to": ["91890xx", "91890xx"],
        "type": "document",
        "document": {
            "caption": "doc"
        },
        "callback": "{{callback}}"
    }

To Remove the double quotes, please use replace function as shown below

String  Number1="[\"91890xxx\", \"91890xx\"]";
        Number1.replace("\\/", "");
        System.out.println("Excepted output:"+Number1);
output:

Excepted output:["91890xxx", "91890xx"] 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.