反序列化JSON

时间:2011-08-24 19:53:24

标签: json serialization gson

我使用GSON.toJson将具有字符串和链接的hashmap的Java对象转换为JSON。此过程的输出是键:值对和数组的组合,如下所示:

{"a":"b", "c":"d", "featuremap":{"e":"f", "g":"h"}}

请问您如何将其反序列化为包含键:值对的字符串,即解析featuremap数组,以便输出为:

{"a":"b", "c":"d", "e":"f", "g":"h"}

2 个答案:

答案 0 :(得分:1)

看看GSON doc。 您可以为特定类型编写自己的序列化器/反序列化器

https://sites.google.com/site/gson/gson-user-guide#TOC-Writing-a-Deserializer

How do I write a custom JSON deserializer for Gson?

答案 1 :(得分:1)

这取决于:它总是会成为像

这样的对象
var objToFlatten = {
    "a": "b",
    "c": "d",
    "featuremap": {
        "e": "f",
        "g": "h"
    }
}

或者它可能是多嵌套的,多个对象要展平?例如:

var objToFlatten = {
    "a": "b",
    "c": "d",
    "featuremap": {
        "e": "f",
        "g": "h"
    },
    "someothermap": {
        "e": "f",
        "g": "h",
        "nestedmap": {
            "i": "j"
        }
    }
}

第一个很容易,但是很黑。

function copyFromObject(other) {
    for (var propertyName in other) {
        if (propertyName == 'featureMap') continue;
        if (other.hasOwnProperty(propertyName)) {
            this[propertyName] = other[propertyName];
        }
    }
    return this;
}
var flattened = copyFromObject.call({}, objToFlatten);

后者会更清洁,需要递归解决方案。此外,您还需要弄清楚您要对重复条目等内容做些什么。如果两个具有相同名称的嵌套对象中有两个属性,该怎么办?