gson 解析双引号上的Json时出现问题

pdsfdshx  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(290)

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

{
    "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个反斜杠。但在编程中,我如何知道哪一个引号要用三个反斜杠转义,哪一个引号要用一个反斜杠转义?

cigdeys3

cigdeys31#

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

jei2mxaa2#

它失败的原因是需要对特殊字符(如"\)进行转义。只需在特殊字符前添加一个反斜杠,就可以了:

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

materialLongDescription也是如此。

相关问题