I\'m new to java so this is a bit confusing
I want to get json formatted string
The result I want is
{ \"user\": [ \"name\", \"lamis\" ] }
Probably what you are after is different than what you think you need;
You should have a separate 'User' object to hold all properties like name, age etc etc. And then that object should have a method giving you the Json representation of the object...
You can check the code below;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class User {
String name;
Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public JSONObject toJson() {
try {
JSONObject json = new JSONObject();
json.put("name", name);
json.put("age", age);
return json;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User lamis = new User("lamis", 23);
System.out.println(lamis.toJson());
}
}
Another way of doing it is to use a JSONArray for presenting a list
JSONArray arr = new JSONArray();
arr.put("name");
arr.put("lamis");
JSONObject json = new JSONObject();
json.put("user", arr);
System.out.println(json); //{ "user": [ "name", "lamis" ] }
Try this:
JSONObject json = new JSONObject();
json.put("user", new JSONArray(new Object[] { "name", "Lamis"} ));
System.out.println(json.toString());
However the "wrong" result you showed would be a more natural mapping of "there's a user with the name "lamis" than the "correct" result.
Why do you think the "correct" result is better?