1

我正在使用 snmp4j 进行 SNMP Walk 结果需要发送到客户端以在 python 中解码以进行进一步分析。我是 json 新手,需要帮助了解将 java 数据类型转换为 json 的最佳方法,以便可以在 python 中轻松解码。我不确定它是否可以在正确的字典或列表中解码,但这样做的任何帮助都会很有用。目前我正在使用 gson 将以下共振转换为 json

[vbs=[1.3.6.1.2.1.2.2.1.2.1 = VLAN1, 1.3.6.1.2.1.2.2.1.2.2 = FastEthernet0/1],status=0,exception=null,report=null]

以下是我执行 json.loads 时的结果

[{u'vbs': [{u'variable': {u'value': [86, 76, 65, 78, 49]}, u'oid': {u'value': [1, 3, 6, 1, 2, 1, 2, 2, 1, 2, 1]}}, {u'variable': {u'value': [70, 97, 115, 116, 69, 116, 104, 101, 114, 110, 101, 116, 48, 47, 49]}, u'oid': {u'value': [1, 3, 6, 1, 2, 1, 2, 2, 1, 2, 2]}}], u'status': 0}]

请帮助理解更好的方式来编码成 json 以便于简单和可用的 python 解码。这里需要java序列化吗?我不确定这意味着什么,但仍然想知道我的问题是否清楚,任何帮助至少为我指出正确的资源都会有很大帮助。

4

1 回答 1

0

好的解决方案是在 java 中使用 HashMap,当它转换为 json 时,可以很容易地解码为字典,而无需任何操作。所以这就是我的做法

//declare a hashmap
HashMap hm = new HashMap();

//loop over the snmp result
for (VariableBinding varBinding : varBindings) {
    hm.put(varBinding.getOid(), varBinding.getVariable().toString());
String js = new Gson().toJson(hm);
//now if you return js as string and do json.loads(js) in python you will get dictionary with oid as key and value as value for all oids.
于 2014-05-14T05:20:34.697 回答