繁体   English   中英

为什么json以这种奇怪的方式表现?

[英]Why is json behaving in this weird manner?

JSON作为KEY有任何保留字吗?

我的Json结构是

dimObject{String:String}
finalObject(String:dimObject}

Line1# JSONObject dimObject=new JSONObject()
Line2# dimObject.put("class",["A","B","c"]);
Line3# dimObject.put("name",["sam"]);
Line4# System.out.print("dimObject#"+dimObject.toString());
Line5# JSONObject finalObject=new new JSONObect();
Line6# finalObject("supplier",dimObject);
Line7# System.out.print("finalObject#"+finalObject.toString());

OUTPUT:

dimObject#{"class":["A","B","c"],"name":["sam"]}
finalObject#{"supplier":{"name":["sam"]}}

所以问题是为什么我的json表现得很奇怪。
我没有将“class”定义为变量名,它只是一个Key。

问题是,如果给出一个参数,“class”是一个关键词或保留词,那么我是如何成功插入Line#2 ,如果它的插入能够在dimObject中那么为什么它不能在finalObject中插入

请帮我解开这个谜

精确代码::

public JSONObject getRequiredAttributesWithValues() {
        List<UserConstraint> constraintList = new ArrayList<UserConstraint>();
        Map<String, FactTableOptimizingInfo> factTableMap = MappingInfo.INSTANCE.
                getFactTableUserNameToFactTableOptimizingInfoMap();
        Map<String, DimensionTableInfo> dimTableMap = MappingInfo.INSTANCE.getDimTableRealNameToObjectMap();
        JSONObject requiredAttributes = getRequiredAttributes();
        JSONObject finalObject = new JSONObject();
        for (Object dimName : requiredAttributes.keySet()) {
            JSONObject dimObject = new JSONObject();
            JSONArray colNames = requiredAttributes.getJSONArray((String) dimName);
            for (Object colName : colNames) {
                List<String> columnList = new ArrayList<String>();
                String dimensionName = (String) dimName;
                String columnName = (String) colName;
                constraintList = new ArrayList<UserConstraint>();
                for (FilterDataStructure filter : this.info.getGlobalFilterList()) {
                    if (filter.getDimName().equals(dimensionName)) {
                        if (filter.getColumnName().equals(columnName)) {
                            AtomicConstraint.ConstraintType type;
                            try {
                                Integer.parseInt(filter.getValue());
                                type = AtomicConstraint.ConstraintType.INTEGER_TYPE;
                            } catch (NumberFormatException e) {
                                type = AtomicConstraint.ConstraintType.STRING_TYPE;
                            }
                            UserConstraint constraint = new UserAtomicConstraint(dimensionName, columnName, 
                                                        AtomicConstraint.getStringToOperator(filter.getOperator()),
                                                        filter.getValue(), type, factTableMap, dimTableMap);
                            constraintList.add(constraint);
                        }
                    }
                }

                columnList.add(columnName);
                List<UserDimensionInfoToBuildQuery> dimList = new ArrayList<UserDimensionInfoToBuildQuery>();
                UserTableAndColInfo groupByInfo = new UserTableAndColInfo(dimensionName, columnName);
                ArrayList<UserTableAndColInfo> groupByInfoList = new ArrayList<UserTableAndColInfo>();
                groupByInfoList.add(groupByInfo);

                UserDimensionInfoToBuildQuery dim = new UserDimensionInfoToBuildQuery(dimensionName, columnList);
                dimList.add(dim);
                UserInfoToBuildQuery.Builder queryBuilder = new UserInfoToBuildQuery.Builder(dimList).
                        groupBy(groupByInfoList);
                if (constraintList != null && !(constraintList.isEmpty())) {
                    if (constraintList.size() > 1) {
                        queryBuilder = queryBuilder.constraints(new UserComplexConstraint(constraintList,
                                ComplexConstraint.Joiner.AND));
                    } else {
                        queryBuilder = queryBuilder.constraints(constraintList.get(0));
                    }
                }
                List<Object> result = (List<Object>) DataAccessor.getData(queryBuilder.build());
                if (result == null) {
                    continue;
                }
                JSONArray valueArray = new JSONArray();

                for (Object row : result) {
                    List<Object> splitRow = (List<Object>) row;
                    valueArray.add(splitRow.get(0).toString());
                }
                dimObject.put(colName, valueArray);
            }
            finalObject.put(dimName, dimObject);
        }
        return finalObject;
    }
}

为了跟进你的观察,JSON遵循JavaScript(或ECMAScript,因为它应该被称为)保留字和是其中之一。

编辑:

虽然涉及javascript,但似乎你可以在引号内使用保留字,我已按如下方式测试:

myObj = {"class" : "Analysis of Algorithms"}; // <--works
myObj = { class  : "Analysis of Algorithms"}; //  <--works
myObj = { class  : "class"}; // <--works
myObj = {"class" :  class }; // <--does not work.

同样有趣的是,我仍然对这个问题感到困惑。 使用JSON我使用javascript的所有技术,所以我不能产生相同的结果。

我在这个网站上找到了JSONObject.java的源文件

编辑 :在您的示例中,您使用Java编写代码。 我不知道你正在使用的JSON的Java实现,但它可能并不严格。 它并不意味着是一个JavaScript解释器或引擎,因此它不会阻止你做一些你不应该做的事情。 这就是为什么你可以像你一样添加“类”键 - 即使它错了,Java方也会让你这样做。 它不会检查以确保您没有使用关键字作为标识符。 当JSON在离开Java世界后被Web浏览器解释时,您将遇到问题,因为现在“类”字具有特殊含义。

class是保留字。 您应该避免将其用作变量名称。 请参阅此处获取保留字列表。

Chrome的JavaScript控制台让我将其用作标识符。 IE8表现不同。 我不能在点符号中使用它,但我可以使用括号表示法。 请参阅a.classa['class']

>>var class = "1"
  "Expected identifier"
>>var a = "1"
undefined
>>a
"1"
>>class
  "Syntax error"
>>var a = {}
undefined
>>a["foo"] = "1"
"1"
>>a["class"] = "2"
"2"
>>a.class
  "Expected identifier"
>>a.foo
"1"
>>a['foo']
"1"
>>a['class']
"2"

关键是,不要使用保留字作为标识符。 您可能无法获得预期的结果。

JSON使用{ "double quotes":"around key/vals" }原因是出于这个原因 - 逃避保留字。

那说,如果你得到有效的 JSON,应该没有问题,因为任何保留字将被"double quotes"转义......

我注意到你在这一行中缺少引用:

finalObject#{"supplier:{"name":["sam"]}}

应该是"supplier" 无论如何你可以改变吗? 还是自动生成?

我不认为您的最小示例正确地复制了您遇到的问题。

使用json.org的json java库,我运行了这个Java代码:

public static void main(String[] args) throws JSONException {
    JSONObject dimObject=new JSONObject();
    dimObject.put("class",new JSONArray(new String[] {"A","B","c"}));
    dimObject.put("name", "sam");
    System.out.println("dimObject#"+dimObject.toString());
    JSONObject finalObject=new JSONObject();
    finalObject.put("supplier",dimObject);
    System.out.println("finalObject#"+finalObject.toString());
}

输出如预期:

dimObject#{"name":"sam","class":["A","B","c"]}
finalObject#{"supplier":{"name":"sam","class":["A","B","c"]}}

暂无
暂无

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

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