gpt4 book ai didi

php - 无法将 JSON 转换为 JSONObject

转载 作者:行者123 更新时间:2023-11-29 17:53:26 25 4
gpt4 key购买 nike

这是我的 php 文件传送的 JSON:

[{"id":"408","punktezahl":"15","name":"testname","email":"hsksjs","datum":"24.01.14 17:11","wohnort":"Vdhdhs","newsletter":"J"}]

当我尝试像这样访问 JSON 对象时

public void connect(){
System.out.println("%%%%%%%%%%%%%%%%%1" );
Thread t = new Thread(){
@Override
public void run() {
try {
System.out.println("%%%%%%%%%%%%%%%%%2" );
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 0);
HttpClient httpClient = new DefaultHttpClient(params);
String urlString = "http://url";
//prepare the HTTP GET call
HttpGet httpget = new HttpGet(urlString);
//get the response entity
HttpEntity entity = httpClient.execute(httpget).getEntity();
System.out.println("%%%%%%%%%%%%%%%%%3" );
if (entity != null) {
//get the response content as a string
String response = EntityUtils.toString(entity);
//consume the entity
entity.consumeContent();

// When HttpClient instance is no longer needed, shut down the connection manager to ensure immediate deallocation of all system resources
httpClient.getConnectionManager().shutdown();

//return the JSON response

JSONObject parentObject = new JSONObject(response);
JSONObject userDetails = parentObject.getJSONObject("output");


String name = userDetails.getString("name");
System.out.println("HEEEEEEEEEEEEEEEEEEEEEEEEEEEE" + name);
}



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

};
t.start();
}

我收到以下错误:

01-24 18:18:21.746: W/System.err(20673): org.json.JSONException: Value [{"id":"408","datum":"24.01.14 17:11","punktezahl":"15","email":"hsksjs","newsletter":"J","wohnort":"Vdhdhs","name":"testname"}] of type org.json.JSONArray cannot be converted to JSONObject
01-24 18:18:21.746: W/System.err(20673): at org.json.JSON.typeMismatch(JSON.java:111)
01-24 18:18:21.746: W/System.err(20673): at org.json.JSONObject.<init>(JSONObject.java:159)
01-24 18:18:21.746: W/System.err(20673): at org.json.JSONObject.<init>(JSONObject.java:172)
01-24 18:18:21.746: W/System.err(20673): at com.wuestenfest.jagdenwilli.Highscore_zeigen$1.run(Highscore_zeigen.java:82)

我的错误在哪里?

最佳答案

您的响应是 JSONArray 而不是 JSOnObject

所以改变

  JSONObject parentObject = new JSONObject(response);

 JSONArray jsonarray = new JSONArray(response); 

你的 JSON

[ // json array node
{ // jsson onject npode
"id": "408",
"punktezahl": "15",
"name": "testname",
"email": "hsksjs",
"datum": "24.01.14 17:11",
"wohnort": "Vdhdhs",
"newsletter": "J"
}
]

我在上面的 json 中也没有看到任何 json 对象 output。所以

    JSONObject userDetails = parentObject.getJSONObject("output"); 

也是错误的。

解析

  JSONArray jsonarray = new JSONArray(response); 
JSONObject jb =(JSONObject) jsonarray.getJSONObject(0);
String name= jb.getString("name");

关于php - 无法将 JSON 转换为 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21338647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com