且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中生成随机JSON字符串?

更新时间:2023-02-17 09:21:15

您可以使用 mockneat 为了做到这一点.这是一个专门生成各种伪"数据的库.查看文档,看看可以伪造"什么以及如何伪造.

You can use mockneat in order to do that. It's a library specialised in generating all kind of "fake" data. Check out the documentation to see what you can "fake" and how.

有一个维基页面,向您展示了如何生成随机JSON :

There is a wiki page that shows you how you can generate a Random JSON:

MockNeat mockNeat = MockNeat.threadLocal();
Gson gson = new GsonBuilder()
                        .setPrettyPrinting()
                        .create();

String json = mockNeat
                     .reflect(UserProfile.class)
                     .field("name", mockNeat.names().full())
                     .field("userName", mockNeat.users())
                     .field("email", mockNeat.emails())
                     .field("profiles",
                                mockNeat.reflect(Profile.class)
                                        .field("profileId", mockNeat.ints().range(100, 1000))
                                        .field("profileAdded", mockNeat.localDates().toUtilDate())
                                        .list(2))
                     .map(gson::toJson) /* Transforms the UserProfile class into a 'pretty' json. */
                     .val();

System.out.println(json);

给出的结果是(当然每次结果都不同):

And the given result is (of course, the results are different each time):

{
  "name": "Cecila Starbird",
  "userName": "moistben",
  "email": "randiexyst@hotmail.co.uk",
  "profiles": [
    {
      "profileId": 964,
      "profileAdded": "Mar 19, 1973 12:00:00 AM"
    },
    {
      "profileId": 854,
      "profileAdded": "Jun 3, 1978 12:00:00 AM"
    }
  ]
}

免责声明:我是图书馆的作者.