How to check for NULL when mapping nested JSON?

Hooshyar

I'm trying to map a nested JSON to the model object, the problem is when it returns null, it will break all the code, I want to check if null do something but not break the app.

THE JSON FILE:

[
    {
        "id": 53,
        "date": "2018-12-28T08:51:11",
        "title": {
            "rendered": "this is for featured"
        },
        "content": {
            "rendered": "\n<p><g class=\"gr_ gr_3 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling\" id=\"3\" data-gr-id=\"3\">sdafkj</g> <g class=\"gr_ gr_10 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace\" id=\"10\" data-gr-id=\"10\">kj</g> <g class=\"gr_ gr_16 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace\" id=\"16\" data-gr-id=\"16\">asd</g> <g class=\"gr_ gr_18 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling\" id=\"18\" data-gr-id=\"18\">kadjsfk</g> kljadfklj sd</p>\n",
            "protected": false
        },
        "excerpt": {
            "rendered": "<p>sdafkj kj asd kadjsfk kljadfklj sd</p>\n",
            "protected": false
        },
        "author": 1,
        "featured_media": 54,
        "_links": {
            "self": [
                {
                    "href": "https://client.kurd.app/wp-json/wp/v2/posts/53"
                }
            ],

        },
        "_embedded": {
            "author": [
                {
                    "id": 1,
                    "name": "hooshyar",

                }
            ],
            "wp:featuredmedia": [
                {
                    "id": 54,

                    "source_url": "https://client.kurd.app/wp-content/uploads/2018/12/icannotknow_22_12_2018_18_48_11_430.jpg",
                    }
                    ]
}
]

CODE FOR MAPPING TO OBJECT:

  featuredMediaUrl = map ["_embedded"]["wp:featuredmedia"][0]["source_url"];

The method 'map' was called on null. Receiver: null [0] which sometimes returns null ;

shadowsheep

Following my comment I suggest you to use a code generation library to parse JSON to JSON Models.

Read this article that explain you how to use (for example) the json_serializable package.

Such libraries takes all the dirty job of generate all the boilerplate code to create your Model classes and they take care of null values as mandatory or not.

For example if you annotate a class Person like that:

@JsonSerializable(nullable: true)
class Person {
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth;
  Person({this.firstName, this.lastName, this.dateOfBirth});
  factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

with (nullable: true) the dart class of your model will skip the null value fields.

enter image description here

UPDATE

Because I'm eager of technology I've given quicktype tool (suggested by Christoph Lachenicht) a try with your example.

I've prepared a mock api and a file example.json providing the JSON you've posted. I've taken only one element, not the array. And you can have a look here example.json.

After installin QuickType I've generate the model class for this json:

quicktype --lang dart --all-properties-optional example.json -o example.dart

Pay attention here to tha cli parameter --all-properties-optional that create null checks for missing fields.

Map<String, dynamic> toJson() => {
    "id": id == null ? null : id,
    "date": date == null ? null : date,
    "title": title == null ? null : title.toJson(),
    "content": content == null ? null : content.toJson(),
    "excerpt": excerpt == null ? null : excerpt.toJson(),
    "author": author == null ? null : author,
    "featured_media": featuredMedia == null ? null : featuredMedia,
    "_links": links == null ? null : links.toJson(),
    "_embedded": embedded == null ? null : embedded.toJson(),
};

Then I've used the Example class in example.dart

var jsonExampleResponse =
    await http.get('https://www.shadowsheep.it/so/53962129/testjson.php');
print(jsonExampleResponse.body);

var exampleClass = exampleFromJson(jsonExampleResponse.body);
print(exampleClass.toJson());

And all went fine.

N.B. Of course when you use this class you have to check if its fields are empty before using them:

print(exampleClass.embedded?.wpFeaturedmedia?.toString());

That's all. I hope to have put you in the rigth direction.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to check if the value from the json Data is null

分類Dev

Deserialize nested json string leads to a null value

分類Dev

Getting null in nested elements when deserializing xml

分類Dev

ignoring null or Optional.empty values when mapping

分類Dev

How to check if 2 values IS NULL

分類Dev

How to check if NSDictionary key is NULL

分類Dev

How to deserialize JSON to object in Swift WITHOUT mapping

分類Dev

RestKit: How to preprocess JSON value before mapping

分類Dev

How do I check if two strings are equal in Java when either one of the strings can be a null?

分類Dev

How do I check for a NULL value when using JSPs GET method?

分類Dev

Lodash mapping of nested collections

分類Dev

Null check vs try/catch when 99% of the time object is not null

分類Dev

Null check vs try/catch when 99% of the time object is not null

分類Dev

Which is better when check a list is null : not null or use Any

分類Dev

Check if a String is null or empty when it's null sometimes and sometimes not

分類Dev

How to not unmarsal nested JSON in Golang

分類Dev

How to check if variable is Null or empty in XSLT?

分類Dev

How to check if a class contains null in Flutter

分類Dev

Handling null nested values when using .Select() in Lambda with Entity Framework

分類Dev

Dozer mapping not working for nested object

分類Dev

Automapper - How to get containing class type when mapping a member?

分類Dev

How to fix the np.cumsum function when mapping a series with regex

分類Dev

How to create an image background fade when mapping an array of images with React

分類Dev

how to access nested Json key values in Golang

分類Dev

How can you extract a nested JSON value?

分類Dev

How to include a nested PropertyBusinessObject in a PropertyBusinessObject json?

分類Dev

How to parse nested Json Arrays with Circe Optics

分類Dev

How to append data to a nested JSON file in Python

分類Dev

How to search into nested JSON by values with Python

Related 関連記事

  1. 1

    How to check if the value from the json Data is null

  2. 2

    Deserialize nested json string leads to a null value

  3. 3

    Getting null in nested elements when deserializing xml

  4. 4

    ignoring null or Optional.empty values when mapping

  5. 5

    How to check if 2 values IS NULL

  6. 6

    How to check if NSDictionary key is NULL

  7. 7

    How to deserialize JSON to object in Swift WITHOUT mapping

  8. 8

    RestKit: How to preprocess JSON value before mapping

  9. 9

    How do I check if two strings are equal in Java when either one of the strings can be a null?

  10. 10

    How do I check for a NULL value when using JSPs GET method?

  11. 11

    Lodash mapping of nested collections

  12. 12

    Null check vs try/catch when 99% of the time object is not null

  13. 13

    Null check vs try/catch when 99% of the time object is not null

  14. 14

    Which is better when check a list is null : not null or use Any

  15. 15

    Check if a String is null or empty when it's null sometimes and sometimes not

  16. 16

    How to not unmarsal nested JSON in Golang

  17. 17

    How to check if variable is Null or empty in XSLT?

  18. 18

    How to check if a class contains null in Flutter

  19. 19

    Handling null nested values when using .Select() in Lambda with Entity Framework

  20. 20

    Dozer mapping not working for nested object

  21. 21

    Automapper - How to get containing class type when mapping a member?

  22. 22

    How to fix the np.cumsum function when mapping a series with regex

  23. 23

    How to create an image background fade when mapping an array of images with React

  24. 24

    how to access nested Json key values in Golang

  25. 25

    How can you extract a nested JSON value?

  26. 26

    How to include a nested PropertyBusinessObject in a PropertyBusinessObject json?

  27. 27

    How to parse nested Json Arrays with Circe Optics

  28. 28

    How to append data to a nested JSON file in Python

  29. 29

    How to search into nested JSON by values with Python

ホットタグ

アーカイブ