1

我正在尝试使用 gson 解析 json。但解析后我的列表总是空的。无法找出错误在哪里。

我的json是这样的

{"d":{"__type":"DealMeDataContract:#SocialEyes.Web.WcfService","DealMe":[{"__type":"DealMe:#SocialEyes.Web.Models","Address":"2075 n power line rd suit 1","CategoryId":"1","CategoryName":"Personal","City":"pompano beach","CreatedDate":"\/Date(1377621018533+0000)\/","DealMeId":"5b9b00d9-e8bf-4197-bd2a-36bc5872359f","Description":"Kick-it is the best phone stand on the market. Works with any phone or any case. Hands free use for watching movies, reading books and more. Get 2 Kick-it Kits now for the price of one. Only $19.99\u000d\u000aYou will not find this Deal Me Anywhere else!","ExpiryDate":"\/Date(1383263940000+0000)\/","HasAgreedTermsAndConditions":true,"ImageUrl":"https:\/\/socialeyesplus.blob.core.windows.net\/prodimages\/image_19bcabce-90cb-4298-9f91-c2c1d0a2161a.jpg","IsNewAddress":false,"LastUpdatedDate":"\/Date(1377621018533+0000)\/","Latitude":26.24161,"Longitude":-80.165909,"PhoneNumber":"(954)-444-8028","PreviousDealAddress":"2075 n power line rd suit 1","PreviousDealCity":"pompano beach","PreviousDealState":"FL","PreviousDealZipCode":"33069","StartDate":"\/Date(1377621017920+0000)\/","State":"FL","StateList":[{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"---Please select a State---","Value":null},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Alabama","Value":"AL"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Alaska","Value":"AK"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Arizona","Value":"AZ"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Arkansas","Value":"AR"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"California","Value":"CA"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Colorado","Value":"CO"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Connecticut","Value":"CT"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Delaware","Value":"DE"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"District of Columbia","Value":"DC"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Florida","Value":"FL"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Georgia","Value":"GA"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Guam","Value":"GU"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Hawaii","Value":"HI"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Idaho","Value":"ID"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Illinois","Value":"IL"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Indiana","Value":"IN"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Iowa","Value":"IA"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Kansas","Value":"KS"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Kentucky","Value":"KY"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Louisiana","Value":"LA"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Maine","Value":"ME"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Maryland","Value":"MD"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Massachusetts","Value":"MA"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Michigan","Value":"MI"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Minnesota","Value":"MN"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Mississippi","Value":"MS"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Missouri","Value":"MO"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Montana","Value":"MT"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Nebraska","Value":"NE"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Nevada","Value":"NV"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"New Hampshire","Value":"NH"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"New Jersey","Value":"NJ"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"New Mexico","Value":"NM"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"New York","Value":"NY"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"North Carolina","Value":"NC"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"North Dakota","Value":"ND"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Ohio","Value":"OH"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Oklahoma","Value":"OK"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Oregon","Value":"OR"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Pennsylvania","Value":"PA"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Puerto Rico","Value":"PR"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Rhode Island","Value":"RI"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"South Carolina","Value":"SC"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"South Dakota","Value":"SD"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Tennessee","Value":"TN"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Texas","Value":"TX"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Utah","Value":"UT"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Vermont","Value":"VT"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Virginia","Value":"VA"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Washington","Value":"WA"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"West Virginia","Value":"WV"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Wisonsin","Value":"WI"},{"__type":"SelectListItem:#System.Web.Mvc","Selected":false,"Text":"Wyoming","Value":"WY"}],"SubCategoryId":"124","SubCategoryName":"Electronics","Title":"Kickit phone stand ","UserId":"6851e89f-4a32-496e-b2b6-ea461f31b3bd","ZipCode":"33069"}],"Status":"Success"}}

要将 json 转换为 java 对象,我创建了一个这样的类

public class AllDeals {


public String _type;
public List<Deal> DealMe = new ArrayList<AllDeals.Deal>();
public String Status;

public List<Deal> getDealList() {

    return DealMe;
}


public static class Deal {

    public String __type;
    public String Address;
    public String CategoryId;
    public String CategoryName;
    public String City;
    public String CreatedDate;
    public String DealMeId;
    public String Description;
    public String ExpiryDate;
    public String HasAgreedTermsAndConditions;
    public String ImageUrl;
    public String IsNewAddress;
    public String LastUpdatedDate;
    public String Latitude;
    public String Longitude;
    public String PhoneNumber;
    public String PreviousDealAddress;
    public String PreviousDealCity;
    public String PreviousDealState;
    public String PreviousDealZipCode;
    public String StartDate;
    public String State;
    public List<AllDeals.StateList>  StateList; 
    public String SubCategoryId;
    public String SubCategoryName;
    public String Title;
    public String UserId;
    public String ZipCode;



}

public static class StateList {

    public String __type;
    public String Selected;
    public String Text;
    public String Value;

}

}

        private final Gson mGson = new Gson();
       AllDeals cateResponse = mGson.fromJson(jsonString, AllDeals.class);

我的列表总是空的无法找出原因

4

3 回答 3

2

为了在不更改初始 JSON 字符串的情况下解决您的解析问题,我添加了一个如下类:

public class Container {
    private AllDeals d;

    @Override
    public String toString() {
        return "Container [d=" + d + "]";
    }

}

所以解析是这样调用的:

package stackoverflow.questions.q18930222;

import com.google.gson.Gson;

public class Q18930222 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String jsonString = "{\"d\":{\"__type\":\"DealMeDataContract\",\"DealMe\":[{\"__type\":\"DealMe\",\"Address\":\"2075 n power line rd  suit 1\",\"CategoryId\":\"1\",\"CategoryName\":\"Personal\",\"City\":\"pompano    beach\",\"CreatedDate\":\"\\/Date(1377621018533+0000)\\/\",\"DealMeId\":\"5b9b00d9-e8bf-4197-bd2a-36bc5872359f\",\"Description\":\" Get 2 Kick-it Kits now for the price of one. Only $19.99\\u000d\\u000aYou welse!\",\"ExpiryDate\":\"\\/Date(1383263940000+0000)\\/\",\"HasAgreedTermsAndConditions\":true,\"ImageUrl\":\"null\",\"IsNewAddress\":false,\"LastUpdatedDate\":\"\\/Date(1377621018533+0000)\\/\",\"Latitude\":26.24161,\"Longitude\":-80.1f909,\"PhoneNumber\":\"(954)-454-88\",\"PreviousDealAddress\":\"2075 ne rd suit 1\",\"PreviousDealCity\":\"pompano beach\",\"PreviousDealState\":\"FL\",\"PreviousDealZipCode\":\"33069\",\"StartDate\":\"\\/Date(11017920+0000)\\/\",\"State\":\"FL\",\"StateList\":[{\"__type\":\"SelectListItem:#SyMvc\",\"Selected\":false,\"Text\":\"---Please select a State---\",\"Value\":null},{\"__type\":\"SelectListItem:#Syseb.Mvc\",\"Selected\":false,\"Text\":\"Alabama\",\"Value\":\"AL\"},{\"__type\":\"SelectListItem:#Sys.Mvc\",\"Selected\":false,\"Text\":\"Alaska\",\"Value\":\"AK\"}],\"SubCategoryId\":\"124\",\"SubCategoryName\":\"Electronics\",\"Title\":\"Kice stand \",\"UserId\":\"b3bd\",\"ZipCode\":\"45469\"}],\"Status\":\"Success\"}}";
        Gson mGson = new Gson();
        Container cateResponse = mGson.fromJson(jsonString, Container.class);
        System.out.println(cateResponse);

    }
}

并给你这个结果(我添加了一个toString方法):

Container [d=AllDeals [_type=null, DealMe=[Deal [__type=DealMe, Address=2075 n power line rd  suit 1, CategoryId=1, CategoryName=Personal, City=pompano    beach, CreatedDate=/Date(1377621018533+0000)/, DealMeId=5b9b00d9-e8bf-4197-bd2a-36bc5872359f, Description= Get 2 Kick-it Kits now for the price of one. Only $19.99
You welse!, ExpiryDate=/Date(1383263940000+0000)/, HasAgreedTermsAndConditions=true, ImageUrl=null, IsNewAddress=false, LastUpdatedDate=/Date(1377621018533+0000)/, Latitude=26.24161, Longitude=-80.1f909, PhoneNumber=(954)-454-88, PreviousDealAddress=2075 ne rd suit 1, PreviousDealCity=pompano beach, PreviousDealState=FL, PreviousDealZipCode=33069, StartDate=/Date(11017920+0000)/, State=FL, StateList=[StateList [__type=SelectListItem:#SyMvc, Selected=false, Text=---Please select a State---, Value=null], StateList [__type=SelectListItem:#Syseb.Mvc, Selected=false, Text=Alabama, Value=AL], StateList [__type=SelectListItem:#Sys.Mvc, Selected=false, Text=Alaska, Value=AK]], SubCategoryId=124, SubCategoryName=Electronics, Title=Kice stand , UserId=b3bd, ZipCode=45469]], Status=Success]]

如果你想避免这个类,你应该在开始和结束时Container改变你的 JSON 字符串。但通常 99% 的 JSON 问题不允许更改已解析的字符串。{"d":}

于 2013-09-21T21:05:15.143 回答
1

我得到了答案。我在开始使用 gson lib 解析这个 json 字符串的类时缺少主要的 json 对象应该是这样的

   public class AllDeals {

public MainDealArray d;

public static class MainDealArray{

    public String __type;
    public List<Deal> DealMe = new ArrayList<AllDeals.Deal>();
    public String Status;

    public List<Deal> getDealList() {

        return DealMe;
    }

}



public static class Deal {

    public String __type;
    public String Address;
    public String CategoryId;
    public String CategoryName;
    public String City;
    public String CreatedDate;
    public String DealMeId;
    public String Description;
    public String ExpiryDate;
    public String HasAgreedTermsAndConditions;
    public String ImageUrl;
    public String IsNewAddress;
    public String LastUpdatedDate;
    public String Latitude;
    public String Longitude;
    public String PhoneNumber;
    public String PreviousDealAddress;
    public String PreviousDealCity;
    public String PreviousDealState;
    public String PreviousDealZipCode;
    public String StartDate;
    public String State;
    public List<AllDeals.StateList>  StateList; 
    public String SubCategoryId;
    public String SubCategoryName;
    public String Title;
    public String UserId;
    public String ZipCode;



}

public static class StateList {

    public String __type;
    public String Selected;
    public String Text;
    public String Value;

}

}

于 2013-09-24T07:13:26.197 回答
0
//Hope this will help u..i m fetching this type of url like this
//create class 

/String Method to fetech data from server
public String sendRequest(String url) {
    String result = "";
    try {

        HttpClient client = new DefaultHttpClient();
        HttpParams httpParameters = client.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);
        HttpConnectionParams.setTcpNoDelay(httpParameters, true);
        HttpGet request = new HttpGet();
        request.setURI(new URI(url));
        HttpResponse response = client.execute(request);
        InputStream ips = response.getEntity().getContent();

        BufferedReader buf = new BufferedReader(new InputStreamReader(ips,
                "UTF-8"));

        StringBuilder sb = new StringBuilder();
        String s;
        while (true) {
            s = buf.readLine();
            if (s == null || s.length() == 0)
                break;
            sb.append(s);

        }
        buf.close();
        ips.close();
        result = sb.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}


//fetch thorug like this

class LoadVideo extends AsyncTask<String,Void,String>{

    ProgressDialog mProgress;

    @Override
    protected void onPreExecute() {
     mProgress=new ProgressDialog(SubCategory.mContext);
     mProgress.setTitle("Fetch Video...");
     mProgress.setMessage("Please Wait...");
     mProgress.setCancelable(false);
     mProgress.show();

    }

    @Override
    protected String doInBackground(String... params) {
        String response="";

        try{
             String url="your url paste here"
             response = sendRequest(url);

        }catch(Exception e){
            e.printStackTrace();
            return "";
        }

        return response;
    }


    @Override
    protected void onPostExecute(String result) {
         if (!result.equalsIgnoreCase("")) {
            try {

                    JSONObject mainObject = new JSONObject(result);

                    if (mainObject.has("ID")) {
                         String id = mainObject.getString("ID");
                    }

                    if (mainObject.has("VideoID")) {
                        mVideoId = mainObject.getString("VideoID");
                    }

                    if (mainObject.has("Title")) {
                        String title = mainObject.getString("Title");
                    }

                    if (mainObject.has("Description")) {
                        String desc = mainObject.getString("Description");
                    }

                    if (mainObject.has("Script")) {
                        String script = mainObject.getString("Script");
                    }

                    if (mainObject.has("Phrases")) {
                        String phrases = mainObject.getString("Phrases");
                    }

                } catch (Exception e) {
                    e.printStackTrace();

                } finally {

                    mProgress.dismiss();

                            }
                         }
于 2013-09-21T07:54:43.473 回答