Subair K
Subair K

Reputation: 1880

How to convert x-www-form-urlencoded string to json in dart?

String source= "BRN=920736&STC=000&RMK=success&TRN=935851295243587"

How to convert the x-www-form-urlencoded string to json in dart?

Upvotes: 1

Views: 466

Answers (2)

Dan Syrstad
Dan Syrstad

Reputation: 1447

Using Uri.splitQueryString works if you don't have repeated field names in the x-www-form-urlencoded form data. However, if you do have repeated fields such as:

a=1234&a=5678&b=9876

you'll need to use Uri(query: source).queryParametersAll. For example:

final source = 'a=1234&a=5678&b=9876';
final fields = Uri(query: source).queryParametersAll;
List<String>? a = fields['a']; // [ '1234', '5678' ]
String? b = fields['b']?.first; // '9876'

Upvotes: 0

jamesdlin
jamesdlin

Reputation: 89995

You can use Uri.splitQueryString to parse a x-www-form-urlencoded query string to a Map<String, String>. Note that both keys and values will be Strings, so if you want to interpret some values as, say, ints, you will need to explicitly parse them (e.g. with int.parse).

Example:

var source = "BRN=920736&STC=000&RMK=success&TRN=935851295243587";
var map = Uri.splitQueryString(source);
print(map); // Prints: {BRN: 920736, STC: 000, RMK: success, TRN: 935851295243587}

Upvotes: 4

Related Questions