2016-06-09 41 views
0

轉換字符串我有一個包含以下JSON數據含JSON來gSonObject

[{"date":"11/8/2014","auther":"nirav kalola","description":"json object parsing using gson library is easy","post_name":"json object parsing"},{"date":"12/8/2014","auther":"nirav kalola","description":"json array parsing using gson library","post_name":"json array parsing"},{"date":"17/8/2014","auther":"nirav kalola","description":"store json file in assets folder and get data when required","post_name":"json parsing from assets folder"}] 

我想將它轉換爲GSON

我嘗試下面的代碼

protected void onPostExecute(String result) { 
     Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show(); 
     //etResponse.setText(result); 
     try { 
      Type listType = new TypeToken<ArrayList<BeanPost>>() { 
      }.getType(); 


      ArrayList<BeanPost> beanPostArrayList = new GsonBuilder().create().fromJson(result, listType); 
      // Above Line gives error 
      // JsonDeserializer could not Deserialize the object 
      StringBuffer postList = new StringBuffer(); 
      for (BeanPost post : beanPostArrayList) { 
       postList.append("\n title: " + post.getPost_name() + 
         "\n auther: " + post.getAuther() + 
         "\n date: " + post.getDate() + 
         "\n description: " + post.getDescription() + "\n\n"); 
      } 



     } 
      catch(Exception e2) 
      { 
        String msg=e2.getLocalizedMessage(); 
       e2.printStackTrace(); 

      } 

    } 

BeanPost的字符串。 java類如下

package com.jobwork.mujahidniaz.ws2; 

/** 
* Created by Mujahid Niaz on 06/09/2016. 
*/ 
import com.google.gson.annotations.SerializedName; 
public class BeanPost { 

@SerializedName("post_name") 
private String post_name; 
@SerializedName("auther") 
private String auther; 
@SerializedName("date") 
private String date; 
@SerializedName("description") 
private String description; 

public BeanPost(String post_name, String auther, String date, String description) { 
    this.post_name = post_name; 
    this.auther = auther; 
    this.date = date; 
    this.description = description; 
} 

public String getPost_name() { 
    return post_name; 
} 

public void setPost_name(String post_name) { 
    this.post_name = post_name; 
} 

public String getAuther() { 
    return auther; 
} 

public void setAuther(String auther) { 
    this.auther = auther; 
} 

public String getDate() { 
    return date; 
} 

public void setDate(String date) { 
    this.date = date; 
} 

public String getDescription() { 
    return description; 
} 

public void setDescription(String description) { 
    this.description = description; 
} 
} 

我已經嘗試了很多谷歌搜索,但無法找到答案,請幫助我。

+0

會發生什麼?你有錯誤嗎?格式不正確?難道沒有gDad嗎? – zapl

+0

實現Serializable你的BeanPost類 –

+0

@RakshitNawani爲什麼? –

回答

0

(未測試的代碼)

首先你必須從你的BeanPost.java創建空的公共構造方法,因爲你有自定義構造函數。

public BeanPost(){} 

Gson gson = new Gson; 
List<BeanPost> myBPost = gson.fromJson(result, List<BeanPost.class>); //i assume that result is your json string 

現在你需要與你的每個人來獲得價值。希望它有幫助