web-dev-qa-db-fra.com

Comment créer un tableau JSON correct dans Java à l'aide de JSONObject

comment puis-je créer un objet JSON comme suit, dans Java à l'aide de JSONObject?

{
    "employees": [
        {"firstName": "John", "lastName": "Doe"}, 
        {"firstName": "Anna", "lastName": "Smith"}, 
        {"firstName": "Peter", "lastName": "Jones"}
    ],
    "manager": [
        {"firstName": "John", "lastName": "Doe"}, 
        {"firstName": "Anna", "lastName": "Smith"}, 
        {"firstName": "Peter", "lastName": "Jones"}
    ]
}

J'ai trouvé beaucoup d'exemples, mais pas exactement ma chaîne JSONArray.

118
user2010955

Voici du code utilisant Java 6 pour vous aider à démarrer:

JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");

JSONArray ja = new JSONArray();
ja.put(jo);

JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);

Edit: Puisqu'il y a eu beaucoup de confusion autour de put vs add, je vais essayer d'expliquer la différence. Dans Java 6 org.json.JSONArray contient la méthode put et dans Java 7 javax.json contient la méthode add.

Un exemple de ceci utilisant le modèle de générateur dans Java 7 ressemble à ceci:

JsonObject jo = Json.createObjectBuilder()
  .add("employees", Json.createArrayBuilder()
    .add(Json.createObjectBuilder()
      .add("firstName", "John")
      .add("lastName", "Doe")))
  .build();
230
Grammin

Je suppose que vous obtenez ce JSON à partir d'un serveur ou d'un fichier et que vous souhaitez créer un objet JSONArray à partir de celui-ci.

String strJSON = ""; // your string goes here
JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue();
// once you get the array, you may check items like
JSONOBject jObject = jArray.getJSONObject(0);

J'espère que cela t'aides :)

13
Naeem A. Malik

Small ne méthode réutilisable peut être écrite pour créer un objet personne json afin d'éviter le code en double

JSONObject  getPerson(String firstName, String lastName){
   JSONObject person = new JSONObject();
   person .put("firstName", firstName);
   person .put("lastName", lastName);
   return person ;
} 

public JSONObject getJsonResponse(){

    JSONArray employees = new JSONArray();
    employees.put(getPerson("John","Doe"));
    employees.put(getPerson("Anna","Smith"));
    employees.put(getPerson("Peter","Jones"));

    JSONArray managers = new JSONArray();
    managers.put(getPerson("John","Doe"));
    managers.put(getPerson("Anna","Smith"));
    managers.put(getPerson("Peter","Jones"));

    JSONObject response= new JSONObject();
    response.put("employees", employees );
    response.put("manager", managers );
    return response;
  }
8
Manasi

S'il vous plaît essayez ceci ... espérons que cela aide

JSONObject jsonObj1=null;
JSONObject jsonObj2=null;
JSONArray array=new JSONArray();
JSONArray array2=new JSONArray();

jsonObj1=new JSONObject();
jsonObj2=new JSONObject();


array.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));

array2.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));

jsonObj1.put("employees", array);
jsonObj1.put("manager", array2);

Response response = null;
response = Response.status(Status.OK).entity(jsonObj1.toString()).build();
return response;
1
MSD