当前位置:   article > 正文

java自动生成json,如何在Java中生成随机JSON字符串?

java class 转json 值随机

I want to test a feature of apache kafka.So I need generate random JSON string in Java.(My production data is JSON format.)

I google it, and I found the sites:

These are not the best answer.

In ruby, the gem faker can generate fake data.

In Java, what library can generate fake data? what library can generate fake JSON string?

解决方案

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.

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"

}

]

}

Disclaimer: I am the author of the library.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/950596
推荐阅读
相关标签
  

闽ICP备14008679号