#1 2016-09-30 22:49:40

2keda
Member
Registered: 2015-02-03
Posts: 2

Problem with JSON Serialization for Dynamic JSON String

Maybe my question is answered somewhere else, but i don't know what exatly i'm searching for.

I have a problem with json serialization, because json string is not always the same.

if there is an error in my request, i got these

{
	"id": "123456",
	"code": "401",
	"state": "FAILED",
	"reff": "aa29",
	"data": {
		"errorMsg": "Unauthorized (1)"
	}
}

or these

{
	"id": "123456",
	"code": "401",
	"state": "FAILED",
	"reff": 0,
	"data": {
		"errorMsg": "Unauthorized (1)"
	}
}

if my request success i got these

{
	"id": "123456",
	"code": "200",
	"state": "OK",
	"reff": "",
	"data": ""
}

or these

{
	"id": "123456",
	"code": "200",
	"state": "OK",
	"reff": "",
	"data": {
		"member_id": "11333355555577777777",
		"count": 2,
		"member": [
			{
				"no": 1,
				"name": "JOHN",
				"bill": 178500
			},
			{
				"no": 2,
				"name": "MAX",
				"bill": 0
			},
		]
	},
	"time": "2s"
}

and maybe i got these too

{
	"id": "123456",
	"code": "200",
	"state": "OK",
	"reff": "",
	"data": {
		"member_id": "11333355555577777777",
		"count": 2,
		"bill": 178500
	},
	"time": "1m2s"
}

and my code is

__TErrMsg = 'errorMsg RawUTF8';
__TTrxResponseValue = 'id RawUTF8 code RawUTF8 state RawUTF8 reff RawUTF8 data{errorMsg: RawUTF8}';

TTextWriter.RegisterCustomJSONSerializerFromText(TypeInfo(TTrxResponseValue),
    __TTrxResponseValue).Options := [soReadIgnoreUnknownFields,
    soWriteHumanReadable];

that code work fine if reff is string, but if reff is integer, i'm unable to retrieve "errorMsg".
And i don't know how to handle json string when my request is succed.

Thank you and sorry for my bad english.

Offline

#2 2016-10-01 08:54:22

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,182
Website

Re: Problem with JSON Serialization for Dynamic JSON String

If reff is an integer, it is not a RawUTF8 any more...
You may try to define reff as a variant, then it should support both kind of input.

Offline

#3 2016-10-01 10:27:51

2keda
Member
Registered: 2015-02-03
Posts: 2

Re: Problem with JSON Serialization for Dynamic JSON String

thanks for your answer, now I've got an idea how to solve this problem. your answer give a hint. thanks

Offline

Board footer

Powered by FluxBB