我在 android studio 中的一段代码已经可靠地工作了数周。每当我尝试通过 localhost 接收 Json(用于在模拟器或我的设备上进行调试并通过 wifi 连接)时,我都会收到错误消息:
com.google.gson.JsonParseException:无法解析 json
但是,如果我连接到远程服务器以获取 JSON Echo,例如:
http://echo.jsontest.com/insert-key-here/insert-value-here/key/value
没有问题。
我已经验证 JSON 是有效的,就像我说它以前对我有用,但我已经在网上仔细检查了它,我什至用一个按钮和一个请求创建了一个新的基本应用程序,但仍然有同样的问题。
代码如下:
public static class PlaceholderFragment extends Fragment {
public static final String ACCOUNT_VIEW_URL = "http://192.168.0.10/~user/tests/accountEcho.php"; //"http://echo.jsontest.com/insert-key-here/insert-value-here/key/value";
Button button;
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_screen, container, false);
button = (Button) rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
netWork();
}
});
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((HomeScreenActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
void netWork() {
Ion.with(getActivity())
.load(ACCOUNT_VIEW_URL)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject result) {
if (null == e) {
// Log.v("onCompleted", "not null");
Log.v("result", ""+result+"");
} else {
// Log.v("onCompleted", "null");
Log.v("on completed", "" + e + "");
}
//TODO:::: JSON STRUCTURE - LOAD DP INTO VIEW
}
});
}
}
}
JSON响应是:
{
"accType": "2",
"firstname": "duracell",
"lastname": "battery"
"house_num": "122",
"addL1": "Brick Lane",
"addL2": "",
"city": "Middx"
}
此外,如果我从计算机上的任何其他应用程序(visualJSON、chromeAdvancedRestClient、safari、firefox 等)访问相同的 localhost 地址,它工作正常并且响应符合预期。
谁能告诉我这是怎么回事??
谢谢