0

As for the script below, I have two different json for single record and multiple record as a list. I can parse the single data using the Person class. For the json with a list, I'm using ther PersonList class but I'm getting an error because the json key result is not needed anymore. Is there a way to parse the list without changing the Person class? Or should I not use the PersonList class and just create a List<Person>?

I saw this example but its only working if the json is a whole list like this

var jsonResponse = convert.jsonDecode(rawJsonMulti) as List;
    return jsonResponse.map((p) => Person.fromJson(p).toList();

Can you show me how to use the above script using my json. Thanks.

import 'dart:convert';
void main() {

  String rawJsonMulti = '{"result": [{"name":"Mary","age":30},{"name":"John","age":25}]}';
  String rawJsonSingle = '{"result": {"name":"Mary","age":30}}';
  
// Working for non list json  
//   final result = json.decode(rawJsonSingle);
//   var obj = Person.fromJson(result);
//   print(obj.name);

  
  final result = json.decode(rawJsonMulti);
  var obj = PersonList.fromJson(result);
  print(obj.listOfPerson[0].name);

}


  class PersonList {
  final List<Person> listOfPerson;

  PersonList({this.listOfPerson});

  factory PersonList.fromJson(Map<String, dynamic> json) {
    var personFromJson = json['result'] as List;

    List<Person> lst =
        personFromJson.map((i) => Person.fromJson(i)).toList();

    return PersonList(listOfPerson: lst);
  }
}


  class Person {
    String name;
    int age;
    
    //will only work on result is not a list
    Person({this.name, this.age});
    factory Person.fromJson(Map<String, dynamic> json) {
      return Person(name: json['result']['name'],
                   age: json['result']['age']);
    }

//  This will work on json with list but not in single
//  factory Person.fromJson(Map<String, dynamic> json) {
//       return Person(name: json['name'],
//                    age: json['age']);
//     }
    

  }
1
  • So you want the code to support both rawJsonMulti and rawJsonSingle ? Commented Jul 14, 2020 at 15:16

2 Answers 2

1

If you convert the dynamic to a List<dynamic> you can map each element in the jsonDecoded list.

Example:

import 'dart:convert';

final decodedJson = jsonDecode(rawJsonMulti) as List<dynamic>;
final personList = decodedJson
    .map((e) => Person.fromJson(
        e as Map<String, dynamic>))
    .toList();

return PersonList(listOfPerson: personList);
```
Sign up to request clarification or add additional context in comments.

Comments

0

Try take a look at this solution where I have fixed your code:

import 'dart:convert';

void main() {
  const rawJsonMulti =
      '{"result": [{"name":"Mary","age":30},{"name":"John","age":25}]}';
  const rawJsonSingle = '{"result": {"name":"Mary","age":30}}';

  final resultMulti = json.decode(rawJsonMulti) as Map<String, dynamic>;
  final personListMulti = PersonList.fromJson(resultMulti);
  print(personListMulti.listOfPerson[0]); // Mary (age: 30)
  print(personListMulti.listOfPerson[1]); // John (age: 25)

  final resultSingle = json.decode(rawJsonSingle) as Map<String, dynamic>;
  final personListSingle = PersonList.fromJson(resultMulti);
  print(personListSingle.listOfPerson[0]); // Mary (age: 30)
}

class PersonList {
  final List<Person> listOfPerson;

  PersonList({this.listOfPerson});

  factory PersonList.fromJson(Map<String, dynamic> json) {
    if (json['result'] is List) {
      final personsFromJson = json['result'] as List;
      return PersonList(listOfPerson: [
        ...personsFromJson
            .cast<Map<String, Object>>()
            .map((i) => Person.fromJson(i))
      ]);
    } else {
      final personFromJson = json['result'] as Map<String, Object>;
      return PersonList(listOfPerson: [Person.fromJson(personFromJson)]);
    }
  }
}

class Person {
  String name;
  int age;

  Person({this.name, this.age});
  factory Person.fromJson(Map<String, dynamic> json) {
    return Person(name: json['name'] as String, age: json['age'] as int);
  }

  @override
  String toString() => '$name (age: $age)';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.