解析Json双引号的问题

时间:2021-05-11 11:09:46

标签: java json gson

我正在使用 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);

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

2 个答案:

答案 0 :(得分:0)

由于您的 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();
}

答案 1 :(得分:0)

它失败了,因为您需要对 "\ 等特殊字符进行转义。 只需在特殊字符前添加反斜杠即可:

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

materialLongDescription 也是如此。

相关问题