将json解析为Object java / groovy

时间:2016-11-11 17:25:42

标签: java json groovy

我使用以下格式跟随json:

 [ 
    ["Rio Branco", "1200401", "MU", "01392", "Acre", "AC", 
        ["PSB", "Marina Silva", 115594, 58.34, "N"], 
        ["PSDB", "A\u00e9cio Neves", 44676, 22.55, "N"], 
        ["PT", "Dilma", 35802, 18.07, "N"], 
        ["PSOL", "Luciana Genro", 648, 0.33, "N"], 
        ["PSC", "Pastor Everaldo", 520, 0.26, "N"], 
        ["PV", "Eduardo Jorge", 346, 0.17, "N"], 
        ["PRTB", "Levy Fidelix", 332, 0.17, "N"], 
        ["PSDC", "Eymael", 155, 0.08, "N"], 
        ["PSTU", "Z\u00e9 Maria", 39, 0.02, "N"], 
        ["PCB", "Mauro Iasi", 25, 0.01, "N"], 
        ["PCO", "Rui Costa Pimenta", 6, 0.0, "N"]
    ]
 ]

如何在没有密钥名称的情况下解析这个json? Java代码或groovy / grails代码。

我这样做......

 def lista = new JsonSlurper().parseText(new File(jsonfilename).text) 
lista.each { 
          //here I want to read the properties of son, but how can I without the key name?? 
    }

1 个答案:

答案 0 :(得分:-1)

您需要按索引引用每个字段。我建议将每个字段分配给地图,这样可以更轻松地使用:

json =''' [ 
    ["Rio Branco", "1200401", "MU", "01392", "Acre", "AC", 
        ["PSB", "Marina Silva", 115594, 58.34, "N"], 
        ["PSDB", "A\u00e9cio Neves", 44676, 22.55, "N"], 
        ["PT", "Dilma", 35802, 18.07, "N"], 
        ["PSOL", "Luciana Genro", 648, 0.33, "N"], 
        ["PSC", "Pastor Everaldo", 520, 0.26, "N"], 
        ["PV", "Eduardo Jorge", 346, 0.17, "N"], 
        ["PRTB", "Levy Fidelix", 332, 0.17, "N"], 
        ["PSDC", "Eymael", 155, 0.08, "N"], 
        ["PSTU", "Z\u00e9 Maria", 39, 0.02, "N"], 
        ["PCB", "Mauro Iasi", 25, 0.01, "N"], 
        ["PCO", "Rui Costa Pimenta", 6, 0.0, "N"]
    ]
]'''

def result = new groovy.json.JsonSlurper().parseText json collect { uf ->
    [
        capital : uf[0],
        state: uf[4],
        candidates : uf[6..-1].collect { candidate ->
            [
                party : candidate[0],
                name : candidate[1]
            ]
        }
    ]
}

assert result[0].capital == "Rio Branco"
assert result[0].state == "Acre"
assert result[0].candidates[0].name == "Marina Silva"
assert result[0].candidates[4].party == "PSC"