Reputation: 86
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.
Upvotes: 0
Views: 1959
Reputation: 1816
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;
}
}
Upvotes: 1
Reputation: 589
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);
Upvotes: 0