JSON.uts 7.3 KB
Newer Older
Y
yurj26 已提交
1 2
import { describe, test, expect, Result } from './tests.uts'

杜庆泉's avatar
杜庆泉 已提交
3 4


杜庆泉's avatar
杜庆泉 已提交
5 6 7
type UserJSON={
	id:string;
	name:string|null;
8 9
}

杜庆泉's avatar
杜庆泉 已提交
10
type PersonJSON = {
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
	/**
	* @JSON_FIELD "a+b"
	*/
	a_b: string;
	/**
	* @JSON_FIELD "a-b"
	*/
	a_b_: number;
	/**
	* @JSON_FIELD "class"
	*/
	_class: boolean;
}


杜庆泉's avatar
杜庆泉 已提交
26

杜庆泉's avatar
杜庆泉 已提交
27

Y
yurj26 已提交
28 29 30 31
export function testJSON() : Result {
    return describe("JSON", () => {
        test('parse', () => {
            const json = `{"result":true, "count":42}`;
32
            const obj = JSON.parse(json) as UTSJSONObject;
Y
yurj26 已提交
33
            expect(obj["count"]).toEqual(42);
lizhongyi_'s avatar
lizhongyi_ 已提交
34
            expect(obj["result"] as boolean).toEqual(true);
Y
yurj26 已提交
35 36 37 38 39 40 41

            const json1 = `{
                "name": "John",
                "age": 30,
                "city": "New York"
              }`;
            const obj1 = JSON.parse(json1);
lizhongyi_'s avatar
lizhongyi_ 已提交
42 43 44 45 46 47
            // expect(obj1).toEqual({
            //     name: 'John',
            //     age: 30,
            //     city: 'New York',
            // });
			expect((obj1! as UTSJSONObject).getString('name')).toEqual("John")
杜庆泉's avatar
杜庆泉 已提交
48 49
			
			
Y
yurj26 已提交
50
            const json2 = '{"string":"Hello","number":42,"boolean":true,"nullValue":null,"array":[1,2,3],"object":{"nestedKey":"nestedValue"}}';
51
            const obj2 = JSON.parse<UTSJSONObject>(json2)!;
lizhongyi_'s avatar
lizhongyi_ 已提交
52 53 54 55 56 57 58 59 60 61
            // expect(obj2).toEqual({
            //     string: 'Hello',
            //     number: 42,
            //     boolean: true,
            //     nullValue: null,
            //     array: [1, 2, 3],
            //     object: {
            //         nestedKey: 'nestedValue',
            //     },
            // });
Y
yurj26 已提交
62 63
            expect(obj2['object']).toEqual({
                nestedKey: 'nestedValue',
lizhongyi_'s avatar
lizhongyi_ 已提交
64 65 66
            })
			expect(obj2.getString("object.nestedKey")).toEqual('nestedValue')
	
杜庆泉's avatar
杜庆泉 已提交
67 68 69 70 71 72 73 74 75 76 77
	
			let json3 = `{"id":"216776999999","name":"小王","grade":1.0,"list":[1,2,3],"address":{"province":"beijing","city":"haidian","streat":"taipingzhuang","other":2},"anyValue":[[null,null]],"obj":{"a":1,"b":false,"c":null},"customClass":{"name":"lisi","age":30},"numList":[1,2,3,null],"list2":[1,2,3,4],"dic":{"1":{"c":[null]}},"dicArr":[{"a":{"c":[null]}},{"b":{"c":1}}]}`
			let obj3 = JSON.parse(json3)! as UTSJSONObject;
			let obj3Address = obj3.getAny("address")!
			console.log(obj3Address)
			expect(obj3Address instanceof UTSJSONObject).toEqual(true)
			let obj3DicArr = obj3.getArray("dicArr")!
			let obj3DicArrFirst = obj3DicArr[0] as UTSJSONObject
			let obj3DicArrFirstA = obj3DicArrFirst['a']
			console.log(obj3DicArrFirstA instanceof UTSJSONObject)
			expect(obj3DicArrFirstA instanceof UTSJSONObject).toEqual(true)
杜庆泉's avatar
杜庆泉 已提交
78 79 80 81
			// 目前仅android 支持,暂不放开
			// let obj3 = JSON.parse<User>(json1);
			// console.log(obj3)
			
Y
yurj26 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
            // const json3 = '["apple","banana","cherry"]';
            // const obj3 = JSON.parse(json3)!;
            // TODO JSON.parse 后数组的类型 无法强转
            // expect(obj3).toEqual(['apple', 'banana', 'cherry']);

            // const json4 = '[1, "two", true, null, {"key": "value"}, ["nested"]]';
            // const obj4 = JSON.parse(json4)!;
            // expect(obj4).toEqual([1, 'two', true, null, { key: 'value' }, ['nested']]);

            // TODO 暂不支持多个参数
            // const json5 = '{"p": 5}';
            // const obj5 = JSON.parse(json5, function (k : string, v : number) : number {
            //     if (k === '') return v;
            //     return v * 2;
            // })!;
            // expect(obj5).toEqual({
            //     p: 10,
            // });

杜庆泉's avatar
杜庆泉 已提交
101

Y
yurj26 已提交
102
            expect(JSON.parse('{}')!).toEqual({});
杜庆泉's avatar
杜庆泉 已提交
103
		
Y
yurj26 已提交
104 105 106 107 108
            // TODO 不支持boolean、string,js端需抹平
            // expect(JSON.parse('true')!).toEqual(true);
            // expect(JSON.parse('"foo"')!).toEqual("foo");
            // expect(JSON.parse('null')!).toEqual(null);
        })
杜庆泉's avatar
杜庆泉 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121
		test('parseObject', () => {
		    const json = `{"result":true, "count":42}`;
		    const obj = JSON.parseObject(json);
		    expect(obj!["count"]).toEqual(42);
		    expect(obj!["result"] as boolean).toEqual(true);
		
		    expect(JSON.parseObject('{}')!).toEqual({});
			
			const json1 = `{
			    "name": "John",
			    "id": "30"
			  }`;
			let obj2 = JSON.parseObject<UserJSON>(json1);
lizhongyi_'s avatar
lizhongyi_ 已提交
122
			expect(obj2!.id).toEqual("30");
杜庆泉's avatar
杜庆泉 已提交
123 124 125 126 127
			
			const json2 = `{
			    "id": "30"
			  }`;
			let obj3 = JSON.parseObject<UserJSON>(json2);
lizhongyi_'s avatar
lizhongyi_ 已提交
128
			expect(obj3!.id).toEqual("30");
杜庆泉's avatar
杜庆泉 已提交
129 130 131 132 133 134
			const json3 = `{
			    "name": "John"
			  }`;
			 let obj4 = JSON.parseObject<UserJSON>(json3);
			expect(obj4).toEqual(null);
		})
杜庆泉's avatar
杜庆泉 已提交
135 136 137 138 139 140 141 142 143 144 145
		test('parseArray', () => {
		    const json1 = `[1,2,3]`;
		    const array1 = JSON.parseArray(json1);
			expect(array1).toEqual([1,2,3]);
			
			const json2 = `[1,"hello world",3]`;
			const array2 = JSON.parseArray(json2);
			expect(array2).toEqual([1,"hello world",3]);
			
			
			const json3 = `[{"name":"John","id":"30"},{"name":"jack","id":"21"}]`;
lizhongyi_'s avatar
lizhongyi_ 已提交
146 147
			const array3 = JSON.parseArray<UTSJSONObject>(json3);
			// expect((array3![0])["name"]).toEqual("John");
杜庆泉's avatar
杜庆泉 已提交
148 149
			
		})
lizhongyi_'s avatar
lizhongyi_ 已提交
150
        test('stringify', () => {     
Y
yurj26 已提交
151 152
            const obj = { name: 'John', age: 30 };
            const json = JSON.stringify(obj);
lizhongyi_'s avatar
lizhongyi_ 已提交
153
            // expect(json).toEqual('{"name":"John","age":30}');
Y
yurj26 已提交
154 155

            const obj1 = { name: 'John', age: 30, address: { city: 'New York', country: 'USA' } };
lizhongyi_'s avatar
lizhongyi_ 已提交
156 157
            const json1 = JSON.stringify(obj1);
            // expect(json1).toEqual('{"address":{"country":"USA","city":"New York"},"name":"John","age":30}');
Y
yurj26 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

            const obj2 = ['apple', 'banana', 'cherry'];
            const json2 = JSON.stringify(obj2);
            expect(json2).toEqual('["apple","banana","cherry"]');

            // TODO 暂不支持多个参数
            // const obj3 = { name: 'John', age: '30' };
            // const replacer = (key : string, value : string) : string => (key === 'name' ? value.toUpperCase() : value);
            // const json3 = JSON.stringify(obj3, replacer);
            // expect(json3).toEqual('{"name":"JOHN","age":"30"}');

            // const obj4 = { name: 'John', age: 30 };
            // const json4 = JSON.stringify(obj4, null, 4);
//             expect(json4).toEqual(`{
//     "name": "John",
//     "age": 30
// }`);
lizhongyi_'s avatar
lizhongyi_ 已提交
175
            // expect(JSON.stringify({ x: 5, y: 6 })).toEqual(`{"x":5,"y":6}`);
Y
yurj26 已提交
176 177
            expect(JSON.stringify([3, 'false', false])).toEqual(`[3,"false",false]`);
            expect(JSON.stringify({})).toEqual('{}');
杜庆泉's avatar
杜庆泉 已提交
178 179 180
			expect(JSON.stringify(1002)).toEqual('1002');
			expect(JSON.stringify(1002.202)).toEqual('1002.202');
			expect(JSON.stringify(null)).toEqual('null');
lizhongyi_'s avatar
lizhongyi_ 已提交
181
			// expect(JSON.stringify(100/0.0)).toEqual('null');
Y
yurj26 已提交
182
            expect(JSON.stringify(true)).toEqual('true');
杜庆泉's avatar
杜庆泉 已提交
183
			expect(JSON.stringify(false)).toEqual('false');
杜庆泉's avatar
杜庆泉 已提交
184 185
			//console.log(JSON.stringify('foo'))
            //expect(JSON.stringify('foo')).toEqual('foo');
杜庆泉's avatar
杜庆泉 已提交
186 187
			expect(JSON.stringify(Math.PI)).toEqual('3.141592653589793');
			expect(JSON.stringify(Math.E)).toEqual('2.718281828459045');
杜庆泉's avatar
杜庆泉 已提交
188 189
			
			
190 191 192 193
        })
	
		test('invalidField', () => {
			let str = "{\"a+b\":\"test1\",\"a-b\":2,\"class\":true}"
杜庆泉's avatar
杜庆泉 已提交
194
			let p = JSON.parseObject<PersonJSON>(str)
195 196
			expect(p?._class).toEqual(true)
			expect(p?.a_b).toEqual("test1")
杜庆泉's avatar
杜庆泉 已提交
197
			
198 199 200 201
			
			let retStr = JSON.stringify(p)
			console.log(retStr)    
		})
杜庆泉's avatar
杜庆泉 已提交
202
		
Y
yurj26 已提交
203
    })
杜庆泉's avatar
杜庆泉 已提交
204 205
	
	
Y
yurj26 已提交
206
}