简体   繁体   English

在 JSON 中编码无效/未编码的字符

[英]Encode invalid/unencoded characters in a JSON

Sometimes I get JSON from a backend that contains unencoded/invalid characters.有时我从包含未编码/无效字符的后端获取 JSON。 For example, they might contain an (unencoded) character with ASCII code 31, which means that when I try to do jsonDecode , it fails.例如,它们可能包含一个 ASCII 码为 31 的(未编码)字符,这意味着当我尝试执行jsonDecode时,它​​会失败。 Don't ask why the JSON-encoding on the backend is broken, it just is.不要问为什么后端的 JSON 编码被破坏了,它就是这样。

Anyway, I was wondering if there is a way to replace all unencoded characters with their encoded representations so I will be able to decode the JSON?无论如何,我想知道是否有办法用它们的编码表示替换所有未编码的字符,以便我能够解码 JSON?

The solution I came up with is this.我想出的解决方案是这样的。 It basically checks every character in the JSON and if it is outside the "safe range" of ASCII 32-255, it JSON-encodes the character, strips any surrounding "" and adds the JSON-encoded representation instead of the unencoded character.它基本上检查 JSON 中的每个字符,如果它在 ASCII 32-255 的“安全范围”之外,它会对字符进行 JSON 编码,剥离任何周围的""并添加 JSON 编码的表示而不是未编码的字符。

It could probably be improved, but it seems to do the job at least.它可能会得到改进,但它似乎至少可以完成这项工作。

/// Replaces all characters that can not exist unencoded in a JSON 
/// with their JSON-encoded representations.
String replaceInvalidJsonCharacters(String json) {
  var charCodes = <int>[];

  for (final int codeUnit in json.codeUnits) {    
    if( codeUnit >= 32 && codeUnit <=255 ){ 
      // ASCII 32...255 are guaranteed to be valid in a JSON
      charCodes.add(codeUnit);
    } 
    else {
      // Json-encode the character and add the encoded version.
      // For characters that are valid in a JSON, the encoded version is the same
      // as the original (possibly surrounded by "").
      String encoded = jsonEncode(String.fromCharCode(codeUnit));
      if( encoded.length > 1 ){
        if( encoded.startsWith('"') ) encoded = encoded.substring(1,encoded.length);
        if( encoded.endsWith('"') ) encoded = encoded.substring(0,encoded.length-1);
      }
      charCodes.addAll(encoded.codeUnits);
    }
  }

  return String.fromCharCodes(charCodes);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM