【问题标题】:Problem with parsing Json double-quotation mark解析Json双引号的问题
【发布时间】:2021-05-11 11:09:46
【问题描述】:

我正在使用 Gson 将 json 转换为 java 对象。这是Gson

{
    "assetClassDetails":[{}],
    "assetClassRequired":null,
    "baseUnitofMeasure":"PMI",
    "bomParent":"Yes",
    "commodityCodeTaric":"84158200",
    "enLanguageKey":"EN",
    "enMaterialLongText":"Lenovo Privacy Filter for 14" Notebooks ( L, T and X1 Carbon)"",
    "grossWeightInKg":null,
    "height":null,
    "heightLengthWidthUnit":null,
    "length":null,"manufacturerPartNumber":"",
    "materialLongDescription":"Lenovo Privacy Filter for 14" Notebooks ( L, T and X1 Carbon)"",
    "physicalCategory":"Physical",
    "volume":null,
    "volumeUnit":null,
    "width":null,
    "xxLanguageKey":null,
    "xxMaterialLongText":null
 }

问题在于属性 enMaterialLongText 和 materialLongDescription。在值内部,它们有引号。Gson 无法解析 json。 我的代码是

Gson gson = new Gson();
OperationalInfo outout = gson.fromJson(inputJson, OperationalInfo.class);

OperationalInfo 类是这样的:

public class OperationalInfo {

private String commodityCodeTaric= null;  //  fETCH FROM db

private String physicalCategory= null; 
private String materialType= null; // ZN01 *
private String productHierarchy= null; // Gnp Hierarchy
private String baseUnitofMeasure= null; // From Database
private String height= null; // Manual enetered
private String length= null; // Manual enetered
private String width= null; // Manual enetered
private String heightLengthWidthUnit= null; // Manual enetered
private String volume= null; // Manual enetered
private String volumeUnit= null; // Manual enetered
private String grossWeightInKg= null; // Manual enetered
private String itemCategoryGroup= null;
private String manufacturerPartNumber= null; // is same as spn
private String bomParent= null;  // yes/No    
private String materialLongDescription= null; // Manual enetered
private String enLanguageKey= null; // EN
private String enMaterialLongText= null; // materialLongDescription
private String xxLanguageKey= null;   //  EN
private String xxMaterialLongText= null;      
private String catalogueGroup = null;
private String pirStatus = null;  // Changed, Add , mark for Delete
private List<AssetClassLedger> assetClassDetails = null;
private Boolean assetClassRequired = null;
...
}

我在输入 json 上尝试过 String.replace() 用“\”替换双引号。

更新: 请参考我的以下代码:

Gson gson = new Gson();
String test = "{\"assetClassRequired\":\"\",\"baseUnitofMeasure\":\"PMI\",\"bomParent\":\"Yes\",\"commodityCodeTaric\":\"84158200\",\"enLanguageKey\":\"EN\",\"enMaterialLongText\":\"Lenovo Privacy Filter for 14\\\" Notebooks ( L, T and X1 Carbon)\\\"\",\"grossWeightInKg\":\"\",\"height\":\"\",\"heightLengthWidthUnit\":\"\",\"length\":\"\",\"manufacturerPartNumber\":\"\",\"materialLongDescription\":\"Lenovo Privacy Filter for 14\\\" Notebooks ( L, T and X1 Carbon)\\\"\",\"physicalCategory\":\"Physical\",\"volume\":\"\",\"volumeUnit\":\"\",\"width\":\"\",\"xxLanguageKey\":\"\",\"xxMaterialLongText\":\"\"}";
JsonReader reader1 = new JsonReader(new StringReader(test));
reader1.setLenient(true);
OperationalInfo operationalInfo = gson.fromJson(reader1, OperationalInfo.class);

请注意,我为 enMaterialLongText 和 14 英寸的 materialLongDescription 使用了 3 个反斜杠。但是以编程方式,我如何知道要通过三反斜杠转义哪个引号以及要单反斜杠转义哪个引号?

【问题讨论】:

  • 解析失败,因为它是无效的JSON。请让您从中获取 JSON 的一方对其进行正确编码。
  • @Ivar NodeJs 能够用 JSON.parse() 解析这个畸形,java 的问题。
  • No, it doesn't。它是无效的 JSON。 (自己通过a validator 运行它。)
  • @Ivar 同意它不是一个有效的 json,但我必须把它变成有效的 json 然后解析。我的游戏计划是将输入拆分为逗号,用于分隔键值对。但也有逗号内部值。因此,对逗号使用正则表达式,后跟双引号 - (,)[\\s]*([^\"]) 并用字符串文字 COMMA 替换它。现在我需要一个正则表达式照顾嵌套引号。一旦在 java 对象中解析了 json,我就可以将属性更改为具有嵌套引号。
  • 问题是,根本无法保证您正确修复了 JSON。您将需要转义反斜杠,但您无法知道哪个是值的一部分,哪个不是。 Here is a simple example。有两个有效的 JSON,都带有转义的反斜杠。第一个可能是您要查找的那个,但第二个 also 仅转义了反斜杠(除了一些换行符之外没有其他更改,这些在 JSON 中被忽略)。它们都同样有效,程序无法判断您要查找的内容。

标签: java json gson


【解决方案1】:

由于您的 JSON 无效,我会联系 JSON 的来源以获取有效的 JSON。但是,如果您真的没有其他方法来获取有效的 JSON,您可以尝试预先编辑 JSON 以使其大致有效。但由于您无法正确知道 JSON 的样子,因此强烈建议您不要使用此方法。

/**
 * This method tries to escape incorrect quotes. To do this, it looks at which character comes
 * after a quote character, because it assumes that a closed quote character is followed by either
 * a ",", ":", or "\n". However, if none of the characters follows, the quotation mark is
 * escaped.
 * <br />
 * Example Input:
 * <pre>
 *   { "hello": "world " test "", "number": 0 }
 * </pre>
 * Example Output:
 * <pre>
 *   { "hello": "world \" test \"", "number": 0 }
 * </pre>
 *
 * @param json The invalid JSON input
 * @return (Hopefully) correct JSON
 */
private static String tryFixJson(String json) {
  final StringBuilder resp = new StringBuilder();
  final char[] chars = json.toCharArray();
  boolean open = false;
  for (int i = 0; i < chars.length; i++) {
    final char c = chars[i];
    if (c == '"') {
      if (!open) {
        if (i != 0 && chars[i - 1] != '\\') {
          open = true;
        }
      } else if (i != chars.length - 1) {
        if (chars[i - 1] != '\\') {
          final char n = chars[i + 1];
          if (n != ',' && n != ':' && n != '\n') {
            resp.append('\\');
          } else {
            open = false;
          }
        }
      }
    }
    resp.append(c);
  }
  return resp.toString();
}

【讨论】:

  • 我发了answer for a very similar problem,我想你想看看。
  • 嗨@WiktorStribiżew,它不仅非常相似,实际上它是同样的问题和我的问题。感谢您的指导。本来我在考虑 Json 解析,后来才知道是正则表达式问题 - 修复 JSON,然后任何 json 解析器都会解析它。
【解决方案2】:

失败是因为您需要转义特殊字符,例如 "\。 只需在特殊字符前加一个反斜杠就可以了:

{
  "enMaterialLongText": "Lenovo Privacy Filter for 14\" Notebooks ( L, T and X1 Carbon)\""
}

materialLongDescription 也是如此。

【讨论】:

  • 不是真的。 "\ 是 JSON 中唯一可以转义的“不安全”字符。 {}[] 不在其中。
猜你喜欢
  • 2014-03-27
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多