将 Json 解析为 Object 获取异常 begin_object 但为 begin_array

Posted

技术标签:

【中文标题】将 Json 解析为 Object 获取异常 begin_object 但为 begin_array【英文标题】:Parse Json as Object getting exception begin_object but was begin_array 【发布时间】:2019-05-24 11:57:24 【问题描述】:

我想访问 JSON 对象,但在此过程中出现以下异常:

(begin_object 但是是 begin_array )

这是我的 Json

"RequestUserId": "7bb288a4-db12-45af-9e93-5fbb3943aa20", “总计”:1, “总页数”:1, "上一个链接": "", "NextPageLink": "", “数据”: [ “身份证”:29, “标题”:“能源基金”, “描述”:“Diamerbasha 大坝基金”, “终止”:“收集”, “状态”:“活动”, “金额”:2000, “开始”:空, “结束”:空, "创建日期": "2018-10-28T05:34:13.333", "修改日期": "2018-10-28T05:34:13.333", “媒体”: [], “收藏”: “金额”:405, “计数”:4 , “贡献”:0, “团体”: “身份证”:162, “标题”:“灰度逻辑” , “用户”: "id": "c0985265-04b4-47e5-adc2-b82660912134", “名字”:“伊姆兰”, "姓氏": "Khattak", "头像": "https://marcoapp.blob.core.windows.net/marco/5eb4e50b-b36c-491d-b292-3aa16a445e54.jpg", "封面图片": "https://marcoapp.blob.core.windows.net/marco/bcb1d889-135d-442c-b2c9-7b03dc3639c3.jpg", “协调”: “纬度”:33.532824, “经度”:73.12971 , “IsOnline”:假, “LastSeen”:“5 分钟前” ]

这是我解析 JSON 的代码块:

if (! CommonFunctions.isNetworkAvailable ()) 
            Toast.makeText (getContext (), "Network Not Available", Toast.LENGTH_SHORT).show ();
            return;
        
        JsonObjectRequest req = new JsonObjectRequest (Request.Method.GET, WebServicesConstants.GET_GROUP_POSTS + groupId + "/campaigns",
                null, new Response.Listener<JSONObject>() 
            @Override
            public void onResponse(JSONObject response)
            
                String sJson = response.toString();

                JsonParser parser = new JsonParser();
                JsonObject responseData = parser.parse(sJson).getAsJsonObject();

                Gson gSon = new Gson();
                CampaignResponse campaignResponse = new CampaignResponse ();
                try 
                    campaignResponse = gSon.fromJson(responseData, CampaignResponse.class);
                catch (Exception e)
                
                    Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                


                if(campaignResponse.getCampaignDataResponses()!=null)
                
                    for (int i=0; i<campaignResponse.campaignDataResponses.size(); i++)
                    
                        CampaignDataResponse campaignDataResponse  = campaignResponse.campaignDataResponses.get (i);
                       // feedList.clear();
                        campaignDataResponses.add (campaignDataResponse);
                    
                

                if (campaignDataResponses.size () > 0) 

                    CampaingsAddapter adapter = new CampaingsAddapter(getContext(), campaignDataResponses);
                    CampaignListView.setAdapter(adapter);

                

            
        , new Response.ErrorListener() 
            @Override
            public void onErrorResponse(VolleyError error)
            
            
        )
        
            @Override
            public Map<String,String> getHeaders()
            
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json; charset=utf-8");
                headers.put("Authorization","Bearer " + CommonFunctions.GetUserToken ());
                return headers;
            
        ;

        req.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        MarcoAppController.getInstance().getcRequestQueue().add(req);

Here is my CampaignResponse Class 

公共类 CampaignResponse

@SerializedName ("RequestUserId")
public String requestedUserId;

@SerializedName ("Total")
public String total;

@SerializedName ("TotalPages")
public String totalPages;

@SerializedName ("PreviousLink")
public String previousLink;

@SerializedName ("NextPageLink")
public String nextPageLink;


@SerializedName ("Data")
public ArrayList<CampaignDataResponse> campaignDataResponses;


public String getRequestedUserId () 
    return requestedUserId;


public void setRequestedUserId (String requestedUserId) 
    this.requestedUserId = requestedUserId;


public String getTotal () 
    return total;


public void setTotal (String total) 
    this.total = total;


public String getTotalPages () 
    return totalPages;


public void setTotalPages (String totalPages) 
    this.totalPages = totalPages;


public String getPreviousLink () 
    return previousLink;


public void setPreviousLink (String previousLink) 
    this.previousLink = previousLink;


public String getNextPageLink () 
    return nextPageLink;


public void setNextPageLink (String nextPageLink) 
    this.nextPageLink = nextPageLink;


public ArrayList<CampaignDataResponse> getCampaignDataResponses() 
    return campaignDataResponses;


public void setCampaignDataResponses(ArrayList<CampaignDataResponse> campaignDataResponses) 
    this.campaignDataResponses = campaignDataResponses;

感谢任何帮助。

【问题讨论】:

等一下,onResponse 已经给了你一个 JSONObject ,你为什么要把它转换成字符串并试图再次解析成 JSONObject? 分享您的 CampaignResponse 课程。 CampaignResponse 与您响应的 Json 之间似乎存在不匹配。 @ChandraniChatterjee 在我的 CampaignResponse 类上方查看 纠正你的pojo。有几个在线门户网站可以为您做到这一点。喜欢this 或this 我的 CampaignResponse 类有什么问题吗?? 【参考方案1】:

使用 DTO 生成器创建您的模型类, https://plugins.jetbrains.com/plugin/7834-dto-generator

创建一个模型类,

package com.kintanpatel;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.List;

public class CampaignResponse 


    @Expose
    @SerializedName("Data")
    private List<Data> Data;
    @Expose
    @SerializedName("NextPageLink")
    private String NextPageLink;
    @Expose
    @SerializedName("PreviousLink")
    private String PreviousLink;
    @Expose
    @SerializedName("TotalPages")
    private int TotalPages;
    @Expose
    @SerializedName("Total")
    private int Total;
    @Expose
    @SerializedName("RequestUserId")
    private String RequestUserId;

    public List<Data> getData() 
        return Data;
    

    public void setData(List<Data> Data) 
        this.Data = Data;
    

    public String getNextPageLink() 
        return NextPageLink;
    

    public void setNextPageLink(String NextPageLink) 
        this.NextPageLink = NextPageLink;
    

    public String getPreviousLink() 
        return PreviousLink;
    

    public void setPreviousLink(String PreviousLink) 
        this.PreviousLink = PreviousLink;
    

    public int getTotalPages() 
        return TotalPages;
    

    public void setTotalPages(int TotalPages) 
        this.TotalPages = TotalPages;
    

    public int getTotal() 
        return Total;
    

    public void setTotal(int Total) 
        this.Total = Total;
    

    public String getRequestUserId() 
        return RequestUserId;
    

    public void setRequestUserId(String RequestUserId) 
        this.RequestUserId = RequestUserId;
    

    public static class Data 
        @Expose
        @SerializedName("User")
        private User User;
        @Expose
        @SerializedName("group")
        private Group group;
        @Expose
        @SerializedName("contribution")
        private int contribution;
        @Expose
        @SerializedName("collection")
        private Collection collection;
        @Expose
        @SerializedName("Media")
        private List<String> Media;
        @Expose
        @SerializedName("ModifiedDate")
        private String ModifiedDate;
        @Expose
        @SerializedName("CreatedDate")
        private String CreatedDate;
        @Expose
        @SerializedName("End")
        private String End;
        @Expose
        @SerializedName("Start")
        private String Start;
        @Expose
        @SerializedName("Amount")
        private int Amount;
        @Expose
        @SerializedName("Status")
        private String Status;
        @Expose
        @SerializedName("Terminate")
        private String Terminate;
        @Expose
        @SerializedName("Description")
        private String Description;
        @Expose
        @SerializedName("Title")
        private String Title;
        @Expose
        @SerializedName("Id")
        private int Id;

        public User getUser() 
            return User;
        

        public void setUser(User User) 
            this.User = User;
        

        public Group getGroup() 
            return group;
        

        public void setGroup(Group group) 
            this.group = group;
        

        public int getContribution() 
            return contribution;
        

        public void setContribution(int contribution) 
            this.contribution = contribution;
        

        public Collection getCollection() 
            return collection;
        

        public void setCollection(Collection collection) 
            this.collection = collection;
        

        public List<String> getMedia() 
            return Media;
        

        public void setMedia(List<String> Media) 
            this.Media = Media;
        

        public String getModifiedDate() 
            return ModifiedDate;
        

        public void setModifiedDate(String ModifiedDate) 
            this.ModifiedDate = ModifiedDate;
        

        public String getCreatedDate() 
            return CreatedDate;
        

        public void setCreatedDate(String CreatedDate) 
            this.CreatedDate = CreatedDate;
        

        public String getEnd() 
            return End;
        

        public void setEnd(String End) 
            this.End = End;
        

        public String getStart() 
            return Start;
        

        public void setStart(String Start) 
            this.Start = Start;
        

        public int getAmount() 
            return Amount;
        

        public void setAmount(int Amount) 
            this.Amount = Amount;
        

        public String getStatus() 
            return Status;
        

        public void setStatus(String Status) 
            this.Status = Status;
        

        public String getTerminate() 
            return Terminate;
        

        public void setTerminate(String Terminate) 
            this.Terminate = Terminate;
        

        public String getDescription() 
            return Description;
        

        public void setDescription(String Description) 
            this.Description = Description;
        

        public String getTitle() 
            return Title;
        

        public void setTitle(String Title) 
            this.Title = Title;
        

        public int getId() 
            return Id;
        

        public void setId(int Id) 
            this.Id = Id;
        
    

    public static class User 
        @Expose
        @SerializedName("LastSeen")
        private String LastSeen;
        @Expose
        @SerializedName("IsOnline")
        private boolean IsOnline;
        @Expose
        @SerializedName("Coordinate")
        private Coordinate Coordinate;
        @Expose
        @SerializedName("CoverPicture")
        private String CoverPicture;
        @Expose
        @SerializedName("ProfilePicture")
        private String ProfilePicture;
        @Expose
        @SerializedName("LastName")
        private String LastName;
        @Expose
        @SerializedName("FirstName")
        private String FirstName;
        @Expose
        @SerializedName("Id")
        private String Id;

        public String getLastSeen() 
            return LastSeen;
        

        public void setLastSeen(String LastSeen) 
            this.LastSeen = LastSeen;
        

        public boolean getIsOnline() 
            return IsOnline;
        

        public void setIsOnline(boolean IsOnline) 
            this.IsOnline = IsOnline;
        

        public Coordinate getCoordinate() 
            return Coordinate;
        

        public void setCoordinate(Coordinate Coordinate) 
            this.Coordinate = Coordinate;
        

        public String getCoverPicture() 
            return CoverPicture;
        

        public void setCoverPicture(String CoverPicture) 
            this.CoverPicture = CoverPicture;
        

        public String getProfilePicture() 
            return ProfilePicture;
        

        public void setProfilePicture(String ProfilePicture) 
            this.ProfilePicture = ProfilePicture;
        

        public String getLastName() 
            return LastName;
        

        public void setLastName(String LastName) 
            this.LastName = LastName;
        

        public String getFirstName() 
            return FirstName;
        

        public void setFirstName(String FirstName) 
            this.FirstName = FirstName;
        

        public String getId() 
            return Id;
        

        public void setId(String Id) 
            this.Id = Id;
        
    

    public static class Coordinate 
        @Expose
        @SerializedName("Longitude")
        private double Longitude;
        @Expose
        @SerializedName("Latitude")
        private double Latitude;

        public double getLongitude() 
            return Longitude;
        

        public void setLongitude(double Longitude) 
            this.Longitude = Longitude;
        

        public double getLatitude() 
            return Latitude;
        

        public void setLatitude(double Latitude) 
            this.Latitude = Latitude;
        
    

    public static class Group 
        @Expose
        @SerializedName("Title")
        private String Title;
        @Expose
        @SerializedName("Id")
        private int Id;

        public String getTitle() 
            return Title;
        

        public void setTitle(String Title) 
            this.Title = Title;
        

        public int getId() 
            return Id;
        

        public void setId(int Id) 
            this.Id = Id;
        
    

    public static class Collection 
        @Expose
        @SerializedName("Count")
        private int Count;
        @Expose
        @SerializedName("Amount")
        private int Amount;

        public int getCount() 
            return Count;
        

        public void setCount(int Count) 
            this.Count = Count;
        

        public int getAmount() 
            return Amount;
        

        public void setAmount(int Amount) 
            this.Amount = Amount;
        
    

下面的代码可以将您的 JSON 转换为您的模型,

 @Override
       public void onResponse(JSONObject response) 
          Log.e("", "work!");
     CampaignResponse item = new Gson().fromJson(response.toString(), CampaignResponse.class);
          Log.e("Test", item.getTotal() + "Done");

      

【讨论】:

【参考方案2】:
try
   
   String tp = response.getString("TotalPages");
   JSONArray data = response.getJSONArray("data");
   JSONObject somedata = response.getJSONArray("data").getJSONObject(0);

catch (JSONException e) 

   e.printStackTrace();

【讨论】:

以上是关于将 Json 解析为 Object 获取异常 begin_object 但为 begin_array的主要内容,如果未能解决你的问题,请参考以下文章

python读取json文件报 No JSON object could be decoded

TypeError: the JSON object must be str, not 'bytes'

将JSON转换为Java Object,如何使用Jackson解析BadgerFish约定

解决Hibernate删除异常:deleted object would be re-saved by cascade

Hive解析Json数据

Python3.4.1异常: 'float' object cannot be interpreted as an integer