2016-11-11 132 views
-3

我有以下JSON這種格式:解析JSON到對象的Java/Groovy的

[ 
    ["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

這個JSON文檔結構是惡夢的東西。 – rmlan

+0

任何線索?@rmlan –

+0

當然。做一些研究,寫一些代碼,並在有特定問題時回來。本網站不是用於轉儲JSON文檔,並要求我們爲您編寫解析器。 – rmlan

回答

-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"