Java:是否可以创建一个带有;变量";领域?
谢谢你的帮助 我有以下情况: 我有一个包含API响应的类:Java:是否可以创建一个带有;变量";领域?,java,Java,谢谢你的帮助 我有以下情况: 我有一个包含API响应的类: public class EventsResponse extends ApiResponse { public JSONArray response; public EventsResponse(Boolean success,RequestHandle requesthandle, JSONArray responsefromapi) { super(success, requesthandle); if
public class EventsResponse extends ApiResponse {
public JSONArray response;
public EventsResponse(Boolean success,RequestHandle requesthandle, JSONArray responsefromapi) {
super(success, requesthandle);
if(responsefromapi!=null)this.response=responsefromapi;
else response=null;
}
public EventsResponse(Boolean success,RequestHandle requesthandle, JSONObject responsefromapi) {
super(success, requesthandle);
if(responsefromapi!=null)this.response=responsefromapi;
else response=null;
}
}
正如您所看到的,这里有些东西不起作用:
如果responsefromapi
是一个JSONObject
我尝试将它分配给response
一个JSONArray
显然不起作用
我想做的是:
将responsefromapi
分配给response
并使response
成为JSONObject
或JSONArray
,具体取决于responsefromapi
的内容
因此,我可以使用一个单类EventsResponse
来处理这两种情况,EventsResponse
将包含一个response
,它是JSONObject
或JSONArray
,具体取决于情况
请问这可能吗
谢谢不是很优雅,但是您可以尝试使用
对象
公共超类来引用您的响应:
public Object response;
...
...
public EventsResponse(Boolean success,RequestHandle requesthandle, JSONArray responsefromapi) {
super(success, requesthandle);
if(response!=null)this.response= (Object)responsefromapi;
else response=null;
}
稍后在代码中使用引用的对象需要Java的反射:
if(response.getClass().equals(JSONArray.class)) {
...
...
JSONArray responseAsJSONArray = (JSONArray)response;
...
}
尝试使用泛型:
public class EventsResponse<K> extends ApiResponse {
public K response;
public EventsResponse(Boolean success, RequestHandle requesthandle, K responsefromapi) {
super(success, requesthandle);
response = responsefromapi;
}
}
公共类事件响应扩展了ApiResponse{
公众反应;
公共事件响应(布尔成功、RequestHandle RequestHandle、K responsefromapi){
超级(成功,请求句柄);
response=responsefromapi;
}
}
你可以这样称呼它:
new EventResponse<JSONObject>(...);
neweventresponse(…);
及
neweventresponse(…);
@LisaAnne。我的理解如下:-
根据我的理解,我们使用JSONObject来存储和传递JSON字符串的值,比如
{name:“LisaAnne”,address:“xyz”,responseArray:[{name1:“n1”},{name1:“n2”}]}。
JSONObject包含键值对,而,
JSONArray包含一个有序对。如果将responseArray的值提取到JSONArray类型的对象中,您将成功
要从响应中获取数组,应使用以下类型的语句
JSONArray response= bigDataResponse.getJSONArray("responseArray");
因此,不可能从JSONObject直接强制转换到JSONArray。您必须获取包含数组的密钥,并使用上面给出的语句获取它。
如果您能给我在JSONObject responsefromapi
和JSONArray responsefromapi
中收到的响应结构,我将能够为您提供更好的解决方案
希望这能有所帮助。一切皆有可能,但对于您不知道确切类型的对象,您打算如何处理?@biziclop我可以检查返回的对象是什么类型的,并相应地采取行动,这就是想法……您的responsefromapi JSONObject是否包含一个值为数组的键,您希望将该数组存储到JSONArray响应中。?@Amal感谢您对Amal的评论,但这不是我想做的,我想严格执行问题中的操作;-)你想写一个类还是使用一个对象?你说得对Peter我编辑了这个问题,thanks@LisaAnne我想他指的是
else response=null代码>多余的部分。响应已null
。您的编辑仍然正确:)
JSONArray response= bigDataResponse.getJSONArray("responseArray");