Dart 将不带引号的字符串转换为 json

问题描述 投票:0回答:3

我正在尝试将字符串转换为 json 字符串。

我得到的字符串:

String myJSON =  '{codigo: 1050, decricao: Mage x, qntd: 1, tipo: UN, vUnit: 10,9, vTotal: 10,90}';

我需要的字符串:

String myJSON =  '{"codigo": "1050", "decricao": "Mage x", "qntd": "1", "tipo": "UN", "vUnit": "10,9", "vTotal": "10,90"}';

有人可以阐明我如何添加引号吗?

json flutter dart tostring
3个回答
4
投票

您可以使用

replaceAll
轻松转换字符串。

代码:

  String myJSON =  '{codigo: 1050, decricao: Mage x, qntd: 1, tipo: UN, vUnit: 10,9, vTotal: 10,90}';
  myJSON = myJSON.replaceAll('{', '{"');
  myJSON = myJSON.replaceAll(': ', '": "');
  myJSON = myJSON.replaceAll(', ', '", "');
  myJSON = myJSON.replaceAll('}', '"}');
  print(myJSON);

输出:

{"codigo": "1050", "decricao": "Mage x", "qntd": "1", "tipo": "UN", "vUnit": "10,9", "vTotal": "10,90"}

0
投票

使用 json encode 转换

    import 'dart:convert';
    const JsonEncoder encoder = JsonEncoder.withIndent('  ');
    String myJSON =  '{codigo: 1050, decricao: Mage x, qntd: 1, tipo: UN, vUnit: 10,9, vTotal: 10,90}';
    String str = encoder.convert(myJSON);

0
投票

我调整了 Maciej Szakacz 的答案以适用于我的用例,它是嵌套的 json。我将提供以下代码:

String jsonAddQuotes(String json){
  json = json.replaceAll('{', '{"');
  json = json.replaceAll(': ', '": "');
  json = json.replaceAll(', ', '", "');
  json = json.replaceAll('}', '"}');
  
  json = json.replaceAll('"{', '{');
  json = json.replaceAll('}"', '}');
  return json;
}

正如对他的回答所评论的那样,如果您在 json 值中使用

:
{
}
,
,这将不起作用。

© www.soinside.com 2019 - 2024. All rights reserved.