0

I want to create org.json.JSONObject from String. the String is "user.phone.num : 00113". the result that i would like to have is org.json.JSONObject object with this format:

{
user: 
     { 
       phone:  {num: 00113}
     }
}

so is there any built in method to achieve this result. Thanks.

6
  • Do you need org.json.JSONObject or maybe just simple String but in JSON format? Commented Jul 3, 2017 at 11:12
  • You may check this link - stackoverflow.com/questions/22042638/… Commented Jul 3, 2017 at 11:15
  • I need org.json.JSONObject. Commented Jul 3, 2017 at 11:16
  • how would be your string if you have json like this {attr1:{attr2:'ebrahim'},att3:'ps'}? Commented Jul 3, 2017 at 11:25
  • @EbrahimPoursadeqi in this case i will have two String the first is attr1.attr2: ebrahim and the second is att3: ps . I build these json object , then i build the global json object Commented Jul 3, 2017 at 11:33

2 Answers 2

1

if every line of your json is splitted yo can try this code

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

/**
 * Created by ebi on 7/3/17.
 */
public class Main {
    public static void main(String[] args) throws JSONException {

        String str = "user.phone.num : 00113";
        String json_str = str_to_json(str);
        JSONObject jsonObject = new JSONObject(json_str);
        System.out.println(jsonObject);
    }

    public static String str_to_json(String jsonByDot){
        int valOffset = jsonByDot.indexOf(":");
        String keys = jsonByDot.substring(0,valOffset).trim();
        String val = jsonByDot.substring(valOffset+1).trim();

        String keysArr[] = keys.split("\\.");
        String output = "";
        for(String key:keysArr){
            output+="{"+key+":";
        }
        output+=val;
        for (int i = 0 ;i<keysArr.length;i++){
            output+="}";
        }

        return  output;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try using below -

    JSONObject obj1 = new JSONObject();
        obj1.put("birthdate", "01-01-2017");
        obj1.put("age", new Integer(18));

   JSONObject obj2 = new JSONObject();
        obj2.put("name", "abc");
        obj2.put("details", obj1);

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.