python构建json_造轮子:像Python一样用Java构建JSON

在后端开发中经常会遇到组装嵌套JSON的情况:

如果你想拼出这样的JSON:

{

"user":"root",

"password":"123456",

"age":12,

"time":"Mon Dec 11 16:32:39 CST 2017",

"number":[

1,

2,

5.0,

6,

7

],

"score":{

"English":99,

"Physical":95,

"Math":88

},

"extra":"extra_value",

"judge1":true,

"append":"^_^"

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

{

"user":"root",

"password":"123456",

"age":12,

"time":"Mon Dec 11 16:32:39 CST 2017",

"number":[

1,

2,

5.0,

6,

7

],

"score":{

"English":99,

"Physical":95,

"Math":88

},

"extra":"extra_value",

"judge1":true,

"append":"^_^"

}

如果你用Python拼:

import json

obj = {

"user": "root",

"password": "123456",

"age": 12,

"time": "Mon Dec 11 16:32:39 CST 2017",

"number": [

1, 2, 5.0, 6, 7

],

"score": {

"English": 99,

"Physical": 95,

"Math": 88

},

"extra": "extra_value",

"judge1": True,

"append": "^_^"

}

print(json.dumps(obj, indent=4))

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

importjson

obj={

"user":"root",

"password":"123456",

"age":12,

"time":"Mon Dec 11 16:32:39 CST 2017",

"number":[

1,2,5.0,6,7

],

"score":{

"English":99,

"Physical":95,

"Math":88

},

"extra":"extra_value",

"judge1":True,

"append":"^_^"

}

print(json.dumps(obj,indent=4))

然而你用Java拼:

package p171211;

import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;

import com.alibaba.fastjson.serializer.SerializerFeature;

import java.math.BigDecimal;

import java.util.Date;

public class Main2 {

public static void main(String[] args) {

JSONObject obj = new JSONObject(true);

obj.put("user", "root");

obj.put("password", "123456");

obj.put("age", 12);

obj.put("time", new Date().toString());

JSONArray number = new JSONArray();

number.add(1);

number.add(2);

number.add(5.0);

number.add(6L);

number.add(new BigDecimal(7.0));

obj.put("number", number);

JSONObject score = new JSONObject();

score.put("Math", 88);

score.put("English", 99);

score.put("Physical", 95);

obj.put("score", score);

obj.put("extra", "extra_value");

if (1 < 2) {

obj.put("judge1", true);

}

if (1 > 2) {

obj.put("judge2", true);

}

obj.put("append", "^_^");

System.out.println(JSONObject.toJSONString(obj, SerializerFeature.PrettyFormat));

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

packagep171211;

importcom.alibaba.fastjson.JSONArray;

importcom.alibaba.fastjson.JSONObject;

importcom.alibaba.fastjson.serializer.SerializerFeature;

importjava.math.BigDecimal;

importjava.util.Date;

publicclassMain2{

publicstaticvoidmain(String[]args){

JSONObjectobj=newJSONObject(true);

obj.put("user","root");

obj.put("password","123456");

obj.put("age",12);

obj.put("time",newDate().toString());

JSONArraynumber=newJSONArray();

number.add(1);

number.add(2);

number.add(5.0);

number.add(6L);

number.add(newBigDecimal(7.0));

obj.put("number",number);

JSONObjectscore=newJSONObject();

score.put("Math",88);

score.put("English",99);

score.put("Physical",95);

obj.put("score",score);

obj.put("extra","extra_value");

if(1<2){

obj.put("judge1",true);

}

if(1>2){

obj.put("judge2",true);

}

obj.put("append","^_^");

System.out.println(JSONObject.toJSONString(obj,SerializerFeature.PrettyFormat));

}

}

造轮子

感觉太繁琐了,要是嵌套层次再深上三四层,就没法写了。。。

然后就造了个轮子...其实就是几个函数而已哈哈 = =

先看看改造后的代码:

public class Main {

public static void main(String[] args) {

JSONObject obj = map(

"user", "root",

"password", "123456",

"age", 12,

"time", new Date().toString(),

"numbers", array(

1, 2, 5.0, 6L, new BigDecimal(7.0)

),

"score", map(

"Math", 88,

"English", 99,

"Physical", 95

),

to("extra", "extra_value"),

to(1 < 2, "judge1", true),

to(1 > 2, "judge2", true),

"append", "^_^"

);

System.out.println(JSONObject.toJSONString(obj, SerializerFeature.PrettyFormat));

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

publicclassMain{

publicstaticvoidmain(String[]args){

JSONObjectobj=map(

"user","root",

"password","123456",

"age",12,

"time",newDate().toString(),

"numbers",array(

1,2,5.0,6L,newBigDecimal(7.0)

),

"score",map(

"Math",88,

"English",99,

"Physical",95

),

to("extra","extra_value"),

to(1<2,"judge1",true),

to(1>2,"judge2",true),

"append","^_^"

);

System.out.println(JSONObject.toJSONString(obj,SerializerFeature.PrettyFormat));

}

}

输出结果:

{

"user":"root",

"password":"123456",

"age":12,

"time":"Mon Dec 11 19:54:56 CST 2017",

"numbers":[

1,

2,

5.0,

6,

7

],

"score":{

"Math":88,

"English":99,

"Physical":95

},

"extra":"extra_value",

"judge1":true,

"append":"^_^"

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

{

"user":"root",

"password":"123456",

"age":12,

"time":"Mon Dec 11 19:54:56 CST 2017",

"numbers":[

1,

2,

5.0,

6,

7

],

"score":{

"Math":88,

"English":99,

"Physical":95

},

"extra":"extra_value",

"judge1":true,

"append":"^_^"

}

虽然看起来还是不那么优雅,不过好多了哈哈!

最后附上轮子的实现代码,我把它称之为JSONCreator,依赖于alibaba的fastjson:

package com.zzkun;

import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;

import java.util.Arrays;

public class JSONCreator {

private static class MapEntry {

String key;

Object value;

MapEntry(String key, Object value) {

this.key = key;

this.value = value;

}

}

public static JSONObject map(Object... arr) {

JSONObject res = new JSONObject(true);

for (int i = 0; i < arr.length; ) {

if (arr[i] == null) {

i += 1;

}

else if (arr[i] instanceof MapEntry) {

MapEntry cur = (MapEntry) arr[i];

res.put(cur.key, cur.value);

i += 1;

}

else {

res.put(arr[i].toString(), arr[i+1]);

i += 2;

}

}

return res;

}

public static MapEntry to(String key, Object value) {

return new MapEntry(key, value);

}

public static MapEntry to(boolean desc, String key, Object value) {

return desc ? new MapEntry(key, value) : null;

}

public static JSONArray array(Object... arr) {

return new JSONArray(new ArrayList(Arrays.asList(arr)));

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

packagecom.zzkun;

importcom.alibaba.fastjson.JSONArray;

importcom.alibaba.fastjson.JSONObject;

importjava.util.ArrayList;

importjava.util.Arrays;

publicclassJSONCreator{

privatestaticclassMapEntry{

Stringkey;

Objectvalue;

MapEntry(Stringkey,Objectvalue){

this.key=key;

this.value=value;

}

}

publicstaticJSONObjectmap(Object...arr){

JSONObjectres=newJSONObject(true);

for(inti=0;i

if(arr[i]==null){

i+=1;

}

elseif(arr[i]instanceofMapEntry){

MapEntrycur=(MapEntry)arr[i];

res.put(cur.key,cur.value);

i+=1;

}

else{

res.put(arr[i].toString(),arr[i+1]);

i+=2;

}

}

returnres;

}

publicstaticMapEntryto(Stringkey,Objectvalue){

returnnewMapEntry(key,value);

}

publicstaticMapEntryto(booleandesc,Stringkey,Objectvalue){

returndesc?newMapEntry(key,value):null;

}

publicstaticJSONArrayarray(Object...arr){

returnnewJSONArray(newArrayList(Arrays.asList(arr)));

}

}

在需要使用只需要import static com.zzkun.JSONCreator.*;,然后就能愉快地使用map, to, array等方法简捷地用Java构建JSON了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值