0

I want to generate custom json from this Model:

class Book {
  List<Route> routes;
  double distance;
  int rateId;
  List<int> optionsIds;
  String comment;
  int regionId;
}

class Route {
  double lat;
  double lng;
  int order;
  String address;
}

var book = Book();
book.routes = [Route(lat: 12, lng: 12, order: 0,address: 'address1'), Route(lat: 12, lng: 12, order: 1,address: 'address2')]; 
book.distance = 10.3;
book.rateId = 0;
book.optionsIds = [1,2];
book.comment = 'book comment';
book.regionId = 1;

I need this json:

{
  "routes[0][address]": "Aviasozlar, 24",
  "routes[0][lat]": 12,
  "routes[0][lng]": 12,
  "routes[0][order]": 0,
  
  "routes[1][address]": "Mustaqillik maydoni",
  "routes[1][lat]": 12,
  "routes[1][lng]": 12,
  "routes[1][order]": 1,
  
  "distance": 12,
  "rate_id": 1,
  "option_ids[]": 1,
  "option_ids[]": 2,
  "comment": "komment 1",
  "region_id": 1,
}

Ignore this text: It looks like your post is mostly code; please add some more details.

Ignore this text: It looks like your post is mostly code; please add some more details.

1 Answer 1

3

Simply create a method toJson to your Book class.

class Book {
  List<Route> routes;
  double distance;
  int rateId;
  List<int> optionsIds;
  String comment;
  int regionId;

  Map<String, dynamic> toJson() {
    Map<String, dynamic> json = {};

    for (int i = 0; i < routes.length; i++) {
      json['routes[$i][address]'] = routes[i].address;
      json['routes[$i][lat]'] = routes[i].lat;
      json['routes[$i][lng]'] = routes[i].lng;
      json['routes[$i][order]'] = routes[i].order;
    }
    
    json['distance'] = distance;
    json['rate_id'] = rateId;
    
    for (int i = 0; i < optionsIds.length; i++) {
      json['option_ids[$i]'] = optionsIds[i];
    }
    
    json['comment'] = comment;
    json['region_id'] = regionId;
    
    return json;
  }
}

Then simply apply jsonEncode to the returned Map<String, dynamic>.

print(jsonEncode(book.toJson()));

Formatted result:

{
   "routes[0][address]":"address1",
   "routes[0][lat]":12,
   "routes[0][lng]":12,
   "routes[0][order]":0,
   "routes[1][address]":"address2",
   "routes[1][lat]":12,
   "routes[1][lng]":12,
   "routes[1][order]":1,
   "distance":10.3,
   "rate_id":0,
   "option_ids[0]":1,
   "option_ids[1]":2,
   "comment":"book comment",
   "region_id":1
}

Try full example on DartPad

Sign up to request clarification or add additional context in comments.

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.