{"id":27390186,"url":"https://github.com/parsodyl/json_string","last_synced_at":"2025-04-13T19:39:20.973Z","repository":{"id":56833410,"uuid":"159488550","full_name":"parsodyl/json_string","owner":"parsodyl","description":"A simple and lightweight JSON data container for Dart and Flutter.","archived":false,"fork":false,"pushed_at":"2023-03-14T13:47:25.000Z","size":69,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-11-17T04:07:33.144Z","etag":null,"topics":["dart","flutter","json","json-string"],"latest_commit_sha":null,"homepage":"https://pub.dev/packages/json_string","language":"Dart","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/parsodyl.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-11-28T11:04:17.000Z","updated_at":"2023-04-06T07:38:23.000Z","dependencies_parsed_at":"2024-11-17T04:07:38.780Z","dependency_job_id":"a49368c4-ec41-41b8-b9db-83339881afa4","html_url":"https://github.com/parsodyl/json_string","commit_stats":null,"previous_names":[],"tags_count":13,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parsodyl%2Fjson_string","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parsodyl%2Fjson_string/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parsodyl%2Fjson_string/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parsodyl%2Fjson_string/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/parsodyl","download_url":"https://codeload.github.com/parsodyl/json_string/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248769802,"owners_count":21158865,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dart","flutter","json","json-string"],"created_at":"2025-04-13T19:39:20.221Z","updated_at":"2025-04-13T19:39:20.954Z","avatar_url":"https://github.com/parsodyl.png","language":"Dart","funding_links":[],"categories":[],"sub_categories":[],"readme":"# json_string\n\n[![Dart CI](https://github.com/parsodyl/json_string/workflows/Dart%20CI/badge.svg)](https://github.com/parsodyl/json_string/actions) [![codecov](https://codecov.io/gh/parsodyl/json_string/branch/master/graph/badge.svg)](https://codecov.io/gh/parsodyl/json_string) [![Pub](https://img.shields.io/pub/v/json_string.svg)](https://pub.dartlang.org/packages/json_string)\n\nA simple and lightweight JSON data container for Dart and Flutter.\n\n## Why?\n\nThe Dart language doesn't have an official way to mark an object as a piece of JSON data. You have to carry it in a simple string and then use `dart:convert` when you need the decoded value. \nFurthermore, since [JsonCodec](https://api.dartlang.org/stable/dart-convert/JsonCodec-class.html) is designed for general purpose, encoding and decoding operations result completely type-unsafe.\n**json_string** not only keeps your JSON data as light as possible, but also encapsulates `dart:convert` directly into it, offering you better [soundness](https://dart.dev/guides/language/sound-dart) and a much clearer syntax.\n\n## Configure\n\nAdd `json_string` to `pubspec.yaml` under the `dependencies` subsection.\n\n```yaml\ndependencies:\n  json_string: ^3.0.1\n```\n## Install\n\nInstall packages from the command line (or using your favourite IDE).\n\nwith **pub**:\n\n```bash\n$ pub get\n```\n\nwith **flutter**:\n\n```bash\n$ flutter pub get\n```\n\n## Import\n\nIn your library, add the following line:\n\n```dart\nimport 'package:json_string/json_string.dart';\n```\n## How to use it\n\nAll you need is the `JsonString` class. This is where your JSON data is stored.\nWhen you create a new instance, your JSON data is **evaluated** and **minified**.\n\n### Overview\n\nCheck if your string represents a valid JSON, simply using the default constructor:\n\n```dart\ntry {\n    final jsonString = JsonString('{\"username\":\"john_doe\",\"password\":\"querty\"}');\n    // ...\n} on JsonFormatException catch (e) {\n    print('Invalid JSON format: $e');\n}\n```\n\nOr just work with null values, if you prefer:\n\n```dart\nfinal jsonString = JsonString.orNull('{\"username\":\"john_doe\",\"password\":\"querty\"}');\n\nif (jsonString == null) {\n    print('Invalid JSON format');\n}\n// ...\n```\n\nThen, access your data through the `source` property:\n\n```dart\nfinal source = jsonString.source;\n\nprint(source); // {\"username\":\"john_doe\",\"password\":\"querty\"}\n```\nOr read the equivalent `decodedValue` object, without using any other library:\n\n```dart\nfinal credentials = jsonString.decodedValue;\n\nprint(credentials['username']); // john_doe\nprint(credentials['password']); // querty\n```\n\n### Encoding\n\nJsonString provides a set of different methods to encode Dart types, all implemented in a **type-safe** way.\n\n#### Plain objects\n\nMark as `Jsonable` your \"json2dart\" style class, so you won't forget to implement the `toJson()` method:\n\n```dart\n// class declaration\nclass User with Jsonable {\n  String username;\n  String password;\n\n  User({\n    required this.username,\n    required this.password,\n  });\n  \n  @override\n  Map\u003cString, dynamic\u003e toJson() =\u003e \u003cString, dynamic\u003e{\n        'username': username,\n        'password': password,\n      };\n}\n\n// encoding\nfinal user = User(username: 'john_doe', password: 'qwerty');\nfinal jsonString = JsonString.encodeObject(user);\n```\n\nOr, provide an `encoder` to specify how to map your object:\n\n```dart\nfinal jsonString = JsonString.encodeObject(user, encoder: (u) =\u003e {\n    'ba': btoa(\"${u.username}:${u.password}\"),\n});\n```\n\n#### Object lists\n\nIn the same way, you can encode a list of objects:\n\n```dart\nfinal userList = [\n    User(username: 'john_doe', password: 'qwerty'),\n    User(username: 'clara_brothers', password: 'asdfgh')\n];\n\n// default encoding\nfinal jsonString1 = JsonString.encodeObjectList(userList);\n\n// custom encoding\nfinal jsonString2 = JsonString.encodeObjectList(userList, encoder: (u) =\u003e {\n    'ba': btoa(\"${u.username}:${u.password}\"),\n});\n```\n\n#### Primitive lists\n\nIf you want to encode a list of primitive values (**int**, **double**, **String**, **bool** or **Null**), use `encodePrimitiveList()`:\n\n```dart\n// integers\nfinal fibonacci = [1, 1, 2, 3, 5, 8, 13];\nfinal jsonString = JsonString.encodePrimitiveList(fibonacci);\n\n// strings\nfinal message = [\"h\", \"e\", \"l\", \"l\", \"o\", \"!\"];\nfinal jsonString = JsonString.encodePrimitiveList(message);\n\n// doubles\nfinal temperatures = [16.0, 18.0, 21.0, 19.0];\nfinal jsonString = JsonString.encodePrimitiveList(temperatures);\n\n// booleans\nfinal flags = [false, false, true, false];\nfinal jsonString = JsonString.encodePrimitiveList(flags);\n\n// nulls\nfinal usefulList = [null, null, null, null];\nfinal jsonString = JsonString.encodePrimitiveList(usefulList);\n```\n#### Primitive values\n\nSometimes you have to encode just a single value, in that case use `encodePrimitiveValue()`:\n\n```dart\n// integer\nfinal answer = 42;\nfinal jsonString = JsonString.encodePrimitiveValue(answer);\n\n// string\nfinal message = \"hello!\";\nfinal jsonString = JsonString.encodePrimitiveValue(message);\n\n// double\nfinal pi = 3.14159;\nfinal jsonString = JsonString.encodePrimitiveValue(pi);\n\n// boolean\nfinal amIaGenius = false;\nfinal jsonString = JsonString.encodePrimitiveValue(amIaGenius);\n\n// null\nfinal usefulValue = null;\nfinal jsonString = JsonString.encodePrimitiveValue(usefulValue);\n```\n\n### Decoding\n\nIt's time to access the Dart counterpart of some JSON data. \nHere json_string helps you with several solutions. You have **properties** for simple general access and **methods** for some finer decoding operations.\n\n#### Properties\n\nWhen you construct a JsonString object, it checks on your behalf if the source represents a valid piece of JSON data, but it doesn’t tell you **what kind of data** it contains.\nIf you don’t know the expected type or you simply don’t care about it, just access the `decodedValue` property. It works every time: \n\n```dart\n// any type\nfinal decodedValue = jsonString.decodedValue;\n```\n\nBut since most of the time you need to cope with big objects or lists, if you have this information before, it is better to use `decodedValueAsMap` or `decodedValueAsList`:\n\n```dart\n// object expected\ntry {\n    final decodedObject = jsonString.decodedValueAsMap;\n    print(decodedObject.runtimeType); // Map\u003cString, dynamic\u003e\n} on JsonDecodingError catch (e) {\n    throw \"This is not an object.\";\n}\n\n// list expected\ntry {\n    final decodedList = jsonString.decodedValueAsList;\n    print(decodedList.runtimeType); // List\u003cdynamic\u003e\n} on JsonDecodingError catch (e) {\n    throw \"This is not a list.\";\n}\n```\n\n#### Methods\n\nDecoding methods are similar to the encoding ones. They simply do the job the other way round.\n\n##### Plain objects and object lists (non-nullable)\n\n```dart\n// class declaration\nclass User {\n  String username;\n  String password;\n\n  User({\n    required this.username,\n    required this.password,\n  });\n\n  static User fromJson(Map\u003cString, dynamic\u003e json) =\u003e User(\n        username: json['username'] as String,\n        password: json['password'] as String,\n      );\n}\n\n// object decoding\nfinal jsonString = JsonString('{\"username\":\"john_doe\",\"password\":\"querty\"}');\n\nfinal user = jsonString.decodeAsObject(User.fromJson);\n\n// object list decoding\nfinal jsonString = JsonString('''[\n  {\"username\":\"john_doe\",\"password\":\"querty\"},\n  {\"username\":\"clara_brothers\",\"password\":\"asdfgh\"}\n]''');\n\nfinal userList = jsonString.decodeAsObjectList(User.fromJson);\n```\n\n##### Plain objects and object lists (nullable)\n\n```dart\n// class declaration\nclass User {\n  String? username;\n  String? password;\n\n  User({\n    this.username,\n    this.password,\n  });\n\n  static User fromJson(Map\u003cString, dynamic\u003e? json) =\u003e User(\n        username: json?['username'] as String?,\n        password: json?['password'] as String?,\n      );\n}\n\n// object decoding\nfinal jsonString = JsonString('null');\n\nfinal user = jsonString.decodeAsNullableObject(User.fromJson);\n\n// object list decoding\nfinal jsonString = JsonString('''[\n  {\"username\":\"john_doe\",\"password\":\"querty\"},\n  null\n]''');\n\nfinal userList = jsonString.decodeAsNullableObjectList(User.fromJson);\n```\n\n##### Primitive lists\n\n```dart\n// integer list decoding\nfinal jsonString = JsonString('[1, 1, 2, 3, 5, 8, 13]');\nfinal fibonacci = jsonString.decodeAsPrimitiveList\u003cint\u003e();\n\n// string list decoding\nfinal jsonString = JsonString('[\"h\", \"e\", \"l\", \"l\", \"o\", \"!\"]');\nfinal message = jsonString.decodeAsPrimitiveList\u003cString\u003e();\n\n// double list decoding\nfinal jsonString = JsonString('[16.0, 18.0, 21.0, 19.0]');\nfinal temperatures = jsonString.decodeAsPrimitiveList\u003cdouble\u003e();\n\n// boolean list decoding\nfinal jsonString = JsonString('[false, false, true, false]');\nfinal flags = jsonString.decodeAsPrimitiveList\u003cbool\u003e();\n```\n\n##### Primitive values\n\n```dart\n// integer value decoding\nfinal jsonString = JsonString('42');\nfinal answer = jsonString.decodeAsPrimitiveValue\u003cint\u003e();\n\n// string value decoding\nfinal jsonString = JsonString('hello!');\nfinal message = jsonString.decodeAsPrimitiveValue\u003cString\u003e();\n\n// double value decoding\nfinal jsonString = JsonString('3.14159');\nfinal pi = jsonString.decodeAsPrimitiveValue\u003cdouble\u003e();\n\n// boolean value decoding\nfinal jsonString = JsonString('false');\nfinal amIaGenius = jsonString.decodeAsPrimitiveValue\u003cbool\u003e();\n```\n\n##### Nullable primitive lists and values\n\n```dart\n// nullable integer list decoding\nfinal jsonString = JsonString('[42, null, 25, 74, null]');\nfinal availableAges = jsonString.decodeAsPrimitiveList\u003cint?\u003e();\n\n// nullable integer value decoding\nfinal jsonString = JsonString('null');\nfinal maybeAnswer = jsonString.decodeAsPrimitiveValue\u003cint?\u003e();\n```\n\n### Advanced\n\nHere's a list of some advanced available options.\n\n#### Complex encoding\n\nIf you need to encode complicated structures, you can use `JsonString.encode()` which is just a wrapper around the built-in `dart:convert` [encode](https://api.dartlang.org/stable/dart-convert/JsonCodec/encode.html) method:\n\n```dart\nconst data = [{\n  \"key0\": [1, 2, 3],\n  \"key1\": 123,\n  \"key2\": \"123\",\n}, \"value1\", false];\ntry {\n  final jsonString = JsonString.encode(data);\n  // ...\n} on JsonEncodingError catch (e) {\n  print('${data.toString()} is impossible to encode : $e');\n}\n```\n\n#### Caching\n\nDecoding operations may take time and be expensive in terms of computing resources. When you construct a JsonString object, you can specify an `enableCache` flag, which keeps a copy of the `decodedValue` property. This makes every usage of decoding properties or methods **way faster**. The only drawback to this is the necessary memory occupation:\n\n```dart\nfinal jsonString = JsonString(source, enableCache: true);\nfinal decodedMap = jsonString.decodedValueAsMap; // immediate access\n```\n\n#### Turn off Jsonable check\n\nIf you don't want to use `Jsonable`, you can set `checkIfJsonable` to **false** when encoding objects.\n\n```dart\n// singleObject is not a Jsonable object\nfinal jsonString = JsonString.encodeObject(singleObject, checkIfJsonable: false);\n// objectList is not a list of Jsonable objects\nfinal jsonString = JsonString.encodeObjectList(objectList, checkIfJsonable: false);\n```\n\n## Contribute\n\nIf you find a bug, or you would like to see a new feature, please create an [issue](https://github.com/parsodyl/json_string/issues). \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fparsodyl%2Fjson_string","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fparsodyl%2Fjson_string","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fparsodyl%2Fjson_string/lists"}