-2

how do I make such a Json? I use a regular JSONObject and Array Json and don't understand how to create exactly such a Json object

        Faker faker = new Faker();
        JSONObject json = new JSONObject();

        json.put("lastName", faker.name().lastName());
        json.put("firstName", faker.name().firstName());

        json.put("phoneNumber", faker.phoneNumber());
        json.put("amount", 1001);

        return json;

I want to get in such a JSON

{
  "pays":[
    {
      "lastName": "Kek",
      "firstName": "lol",
      "phoneNumber": 4325454555,
      "amount": 1000
    },
    {
      "lastName": "Alex",
      "firstName": "Lol",
      "phoneNumber": 9170067401,
      "amount": 1000
    }
  ]
}
5
  • Seems about right. What's the problem? Commented Jun 15, 2023 at 9:34
  • I don't know how to generate 5 users of a similar nature in the pay array and all in a JSON object. Commented Jun 15, 2023 at 9:37
  • 2
    You'll need another JSONObject with a pays key and a JSONArray value Commented Jun 15, 2023 at 9:39
  • Probably the root problem is "how to make an array in JSON from Java". Here a solution: stackoverflow.com/questions/13268799/create-a-jsonarray Commented Jun 19, 2023 at 8:34
  • Does this answer your question? Create a JSONArray Commented Jun 19, 2023 at 8:34

1 Answer 1

0

Your code:

Faker faker = new Faker();
JSONObject json = new JSONObject();

json.put("lastName", faker.name().lastName());
json.put("firstName", faker.name().firstName());

json.put("phoneNumber", faker.phoneNumber());
json.put("amount", 1001);

return json;

Updated Code:

Faker faker = new Faker();
JSONObject json = new JSONObject();

json.put("lastName", faker.name().lastName());
json.put("firstName", faker.name().firstName());

json.put("phoneNumber", faker.phoneNumber());
json.put("amount", 1001);

// updated here
JSONArray jsonArray=new JSONArray();
jsonArray.put(json);

JSONObject finalJson = new JSONObject(); 
finalJson.put("pays",jsonArray);

return finalJson;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.