0

Как мне запарсить json ответ, если он приходит не в форме map, а в форме list?

[
{
"id" : 10,
"name" : Роза темно-розовая, 50 см,
"image" : https://flowers-1.ru/uploads/product/8/138/preview/dcf4f940dedea02d7a19596c3888c525_big.jpg,
"price" : 109,
"category" : Роза,
"tab" : цветы,
"description" : Темно-розовая роза высотой 50 см. Страна - Эквадор.,
"left_in_stock" : 74,
"size" : small,
"times_bought" : 0,
"times_liked" : 1
}
]
3
  • -{ это опечатка?
    – MiT
    26 дек 2020 в 15:28
  • Вообще тут видно грубые нарушения json формата...
    – MiT
    26 дек 2020 в 15:28
  • да, действительно,поправил
    – fluffix
    27 дек 2020 в 16:53

2 ответа 2

1

let msg = `[
-{
"id" : 10,
"name" : Роза темно-розовая, 50 см,
"image" : https://flowers-1.ru/uploads/product/8/138/preview/dcf4f940dedea02d7a19596c3888c525_big.jpg,
"price" : 109,
"category" : Роза,
"tab" : цветы,
"description" : Темно-розовая роза высотой 50 см. Страна - Эквадор.,
"left_in_stock" : 74,
"size" : small,
"times_bought" : 0,
"times_liked" : 1
}
]`;

// По сути - вся работа - 2 регулярки
const res = msg.replace(/-{/g,'{').replace(/^("[^"]+")\s*\:\s*(.*?)(,?)$/mg,'$1:"$2"$3');
console.log(res);

/*** Вот до сюда можно реализовать на flutter ***/

// а остальное - уже по желанию
const res2 = JSON.parse(res).map(obj=>
  Object.fromEntries(Object.entries(obj)
    .map(([prop,val])=>([prop,isNaN(val)?val:Number(val)]))));
console.log(res2);

На flutter наверное где-то так:

final res = msg.replaceAllMapped(RegExp(r'/-{/'), (match) {
  return '}';
}).replaceAllMapped(RegExp(r'/^("[^"]+")\s*\:\s*(.*?)(,?)$/'), (match) {
  return '${match.group(1)}:"${match.group(2)}"${match.group(3)}';
});
print(res);
1

Прочтите этот ответ.

import 'dart:convert';

List<Data> dataFromJson(String str) => List<Data>.from(json.decode(str).map((x) => Data.fromJson(x)));

String dataToJson(List<Data> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Data {
    Data({
        this.id,
        this.name,
        this.image,
        this.price,
        this.category,
        this.tab,
        this.description,
        this.leftInStock,
        this.size,
        this.timesBought,
        this.timesLiked,
    });

    final String id;
    final String name;
    final String image;
    final String price;
    final String category;
    final String tab;
    final String description;
    final String leftInStock;
    final String size;
    final String timesBought;
    final String timesLiked;

    factory Data.fromJson(Map<String, dynamic> json) => Data(
        id: json["id"] == null ? null : json["id"],
        name: json["name"] == null ? null : json["name"],
        image: json["image"] == null ? null : json["image"],
        price: json["price"] == null ? null : json["price"],
        category: json["category"] == null ? null : json["category"],
        tab: json["tab"] == null ? null : json["tab"],
        description: json["description"] == null ? null : json["description"],
        leftInStock: json["left_in_stock"] == null ? null : json["left_in_stock"],
        size: json["size"] == null ? null : json["size"],
        timesBought: json["times_bought"] == null ? null : json["times_bought"],
        timesLiked: json["times_liked"] == null ? null : json["times_liked"],
    );

    Map<String, dynamic> toJson() => {
        "id": id == null ? null : id,
        "name": name == null ? null : name,
        "image": image == null ? null : image,
        "price": price == null ? null : price,
        "category": category == null ? null : category,
        "tab": tab == null ? null : tab,
        "description": description == null ? null : description,
        "left_in_stock": leftInStock == null ? null : leftInStock,
        "size": size == null ? null : size,
        "times_bought": timesBought == null ? null : timesBought,
        "times_liked": timesLiked == null ? null : timesLiked,
    };
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.