简体   繁体   English

解析Json双引号的问题

[英]Problem with parsing Json double-quotation mark

I am using Gson to convert a json to java object.我正在使用 Gson 将 json 转换为 java ZA8CFDE6331BD59EB2AC96F8911C4B6 Here is the Gson这是 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
 }

Problem is with the attributes enMaterialLongText & materialLongDescription.问题在于属性 enMaterialLongText 和 materialLongDescription。 Inside value they have quotation marks.Gson fails to parse json.内部值有引号。Gson 无法解析 json。 My code is我的代码是

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

OperationalInfo class is like this: OperationalInfo class 是这样的:

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;
...
}

I have tried String.replace() on input json to replace double quotation mark with "\".我已尝试在输入 json 上使用 String.replace() 将双引号替换为“\”。

Update: Pl refer my following code:更新:请参考我的以下代码:

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);

Pl see that I have used 3 back-slashes for enMaterialLongText & materialLongDescription for 14 inch.请看到我为 enMaterialLongText 和 14 英寸的 materialLongDescription 使用了 3 个反斜杠。 But programmatically how will I know which quotation mark to escape by triple-backslash & which one to single-backslash?但是以编程方式,我如何知道要通过三反斜杠转义哪个引号以及要单反斜杠转义哪个引号?

Since your JSON is invalid, I would contact the source of the JSON to get a valid JSON.由于您的 JSON 无效,我将联系 JSON 的来源以获得有效的 JSON。 But if you really have no other way to get a valid JSON, you can try to edit the JSON beforehand to make it approximately valid.但是如果你真的没有其他方法可以获得有效的 JSON,你可以尝试事先编辑 JSON 使其大致有效。 But since you can't know what the JSON looks like correctly, I strongly advise you not to use this method.但是由于您无法正确了解 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();
}

It fails because you need to escape special characters like " and \ . Just add a backslash before the special character and you'll be fine:它失败了,因为您需要转义特殊字符,例如"\ 。只需在特殊字符前添加一个反斜杠就可以了:

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

Same goes for materialLongDescription . materialLongDescription也是如此。

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

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