2013-06-11 86 views
1

嗨,我有一個JSON格式如下我如何轉換JSON到Java對象

{ 
"elements":[ 
     list1, 
     list2, 
     list3 
    ] 
} 

其中列表1,列表2,項目list3都是JavaScript數組。

現在我可以從JavaScript文件傳遞給我的控制器(我正在使用spring mvc)。現在我想使用正在發送的JSON中的數據。我想把它映射到一個模型類並返回另一個jsp頁面。 我還沒有創建模型。我怎麼能把這個關掉?

請幫忙。提前致謝。

+0

看看傑克遜庫 –

+0

我已經張貼的答案,但如果你提供有關'list1','list2'和'的內容信息list3',我們可以給出更精確的解決方案... – MikO

回答

2

使用GSON你的JSON轉換成Java

YourModelClass obj= gson.fromJson(json, YourModelClass .class); 
+0

感謝您分享代碼@NullPointerException。這對我幫助很大。 – user2182000

2

使用Gson,你首先需要創建一個類結構,代表你的JSON數據,這樣你就可以創建這樣一個類:

public class Response { 
    private List<List<YourObject>> elements; 
    //getter and setter 
} 

請注意,我使用YourObject類,因爲您沒有指定數組包含的類型......如果數組僅包含字符串,例如,請將YourObject替換爲String。如果數組包含不同的對象,你必須創建一個表示你的JSON數據,如類:

public class YourObject { 
    private String attribute1; 
    private int attribute2; 
    private boolean attribute3; 
    //getters and setters 
} 

然後,實際上爲了解析您的JSON響應,你就必須做到:

Gson gson = new Gson(); 
Response response = gson.fromJson(yourJsonString, Response.class); 

而且你的JSON數據將被用來填補你的類結構,以便您可以訪問的字段,例如:

String attribute1 = response.getElements().get(i).get(i).getAttribute1(); 
+0

感謝您的答案@MikO。我需要更多練習json轉換。 – user2182000

0

您好我用下面的代碼和它的工作太棒了。

Gson gson = new Gson(); 
    JsonParser jsonParser = new JsonParser(); 
    JsonArray jsonArray = jsonParser.parse(this.plan).getAsJsonArray(); 
    ArrayList<PlanJson> planJsonList = new ArrayList<PlanJson>(); 
    for(JsonElement jsonElement:jsonArray) 
    { 
     System.out.println(jsonElement); 
     PlanJson planJson = gson.fromJson(jsonElement, PlanJson.class); 
     planJsonList.add(planJson); 
    } 

我發現它是我的json結構中最容易解決的問題。

0

您可以使用傑克遜庫。見:http://jackson.codehaus.org/

下面是一個例子:http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

package com.mkyong.core; 

import java.io.File; 
import java.io.IOException; 
import org.codehaus.jackson.JsonGenerationException; 
import org.codehaus.jackson.map.JsonMappingException; 
import org.codehaus.jackson.map.ObjectMapper; 

public class JacksonExample { 
    public static void main(String[] args) { 

    ObjectMapper mapper = new ObjectMapper(); 

    try { 

     // read from file, convert it to user class 
     User user = mapper.readValue(new File("c:\\user.json"), User.class); 

     // display to console 
     System.out.println(user); 

    } catch (JsonGenerationException e) { 

     e.printStackTrace(); 

    } catch (JsonMappingException e) { 

     e.printStackTrace(); 

    } catch (IOException e) { 

     e.printStackTrace(); 

    } 

    } 

} 
+0

感謝這個替代@meewoK。但是我並沒有試圖在應用程序中添加庫。 – user2182000

+0

@ user2182000 ok,沒問題:) –