简体   繁体   中英

java : create nested json object from String

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM