So erstellen Sie mit JSONObject das richtige JSONArray in Java


129

Wie kann ich in JS mit JSONObject ein JSON-Objekt wie das folgende erstellen?

{
    "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"}
    ]
}

Ich habe viele Beispiele gefunden, aber nicht genau meine JSONArray-Zeichenfolge.

Antworten:


247

Hier ist ein Code, der Java 6 verwendet, um Ihnen den Einstieg zu erleichtern:

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

Bearbeiten: Da es viel Verwirrung über putvs addhier gegeben hat, werde ich versuchen, den Unterschied zu erklären. In Java 6 enthält org.json.JSONArray die putMethode und in Java 7 enthält javax.json die addMethode.

Ein Beispiel für die Verwendung des Builder-Musters in Java 7 sieht ungefähr so ​​aus:

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

3
vielleicht auch in try / catch einwickeln? (oder die Methode muss eine
— Wurfanweisung

8
JSONArray hat keine Put-Methode.
— Jim

2
benutze add statt put
— CleanX

1
@PT_C yep JsonObject jo = Json.createObjectBuilder (); jo.add ("Vorname", "John"); jo.add ("Nachname", "Doe"); jo.build ();
— Grammin

1
@ArnoldBrown Um mainObj ein Array hinzuzufügen, muss es einen Schlüssel haben.
— Grammin

15

Ich nehme an, Sie erhalten diesen JSON von einem Server oder einer Datei und möchten daraus ein JSONArray-Objekt erstellen.

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

Hoffe das hilft :)


11

Es kann eine kleine wiederverwendbare Methode zum Erstellen eines Personen-Json-Objekts geschrieben werden, um doppelten Code zu vermeiden

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

1

Bitte versuchen Sie dies ... hoffe, es hilft

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;
Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.