问题描述
我需要咨询关于我的code。
我试图解析由PHP函数生成的JSON数组 json_en code()
。
我的JSON:
{数据: [{\"streamer\":\"froggen\",\"yt_length\":\"25078\"},{\"streamer\":\"wingsofdeath\",\"yt_length\":\"8979\"},{\"streamer\":\"guardsmanbob\",\"yt_length\":\"4790\"},{\"streamer\":\"kaostv\",\"yt_length\":\"4626\"},{\"streamer\":\"kungentv\",\"yt_length\":\"3883\"},{\"streamer\":\"destiny\",\"yt_length\":\"3715\"},{\"streamer\":\"zekent\",\"yt_length\":\"3428\"},{\"streamer\":\"athenelive\",\"yt_length\":\"1673\"},{\"streamer\":\"frommaplestreet\",\"yt_length\":\"1614\"},{\"streamer\":\"keyorikeys\",\"yt_length\":\"1410\"},{\"streamer\":\"riotgamesturkish\",\"yt_length\":\"1397\"},{\"streamer\":\"vman7\",\"yt_length\":\"1022\"},{\"streamer\":\"tiensinoakuma\",\"yt_length\":\"967\"},{\"streamer\":\"affenklappe\",\"yt_length\":\"748\"},{\"streamer\":\"teamkeyd\",\"yt_length\":\"747\"},{\"streamer\":\"lagtvmaximusblack\",\"yt_length\":\"683\"},{\"streamer\":\"lolgameru\",\"yt_length\":\"665\"},{\"streamer\":\"gruntartv\",\"yt_length\":\"585\"},{\"streamer\":\"entenzwerg\",\"yt_length\":\"579\"},{\"streamer\":\"lolgameru_cauthonpro\",\"yt_length\":\"506\"},{\"streamer\":\"basickz\",\"yt_length\":\"488\"},{\"streamer\":\"ilysuiteheart\",\"yt_length\":\"491\"},{\"streamer\":\"kireiautumn\",\"yt_length\":\"485\"},{\"streamer\":\"ultimavv\",\"yt_length\":\"471\"}]}$c$c>
Java类:
公共类JSONParser {
静态InputStream为= NULL;
静态的JSONObject jObj = NULL;
静态JSON字符串=;
串响应=;//构造
公共JSONParser(){
}公众的JSONObject getJSONFromUrl(字符串URL){
//使HTTP请求
尝试{
// defaultHttpClient
DefaultHttpClient的HttpClient =新DefaultHttpClient();
HTTPGET httpPost =新HTTPGET(URL); HTT presponse HTT presponse = httpClient.execute(httpPost);
HttpEntity httpEntity = HTT presponse.getEntity();
是= httpEntity.getContent();
}赶上(UnsupportedEncodingException五){
e.printStackTrace();
}赶上(ClientProtocolException E){
e.printStackTrace();
}赶上(IOException异常五){
e.printStackTrace();
} 尝试{
读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
是),8);
StringBuilder的SB =新的StringBuilder();
串线= NULL;
而((行= reader.readLine())!= NULL){
sb.append(行+\\ n);
}
is.close();
JSON = sb.toString();
}赶上(例外五){
Log.e(缓冲区错误,错误转换结果+ e.toString());
} //尝试分析字符串到一个JSON对象
尝试{
jObj =新的JSONObject(JSON);
}赶上(JSONException E){
Log.e(JSON解析器,错误分析数据+ e.toString());
} //返回JSON字符串
返回jObj;
}
}
我的活动:
公共类AndroidJSONParsingActivity扩展ListActivity {
// URL使请求
私有静态字符串URL =http://ololo.tv/vasa;// JSON节点名称
私有静态最后弦乐TAG_DATA =数据;
私有静态最后弦乐TAG_STREAMER =流光
私有静态最后弦乐TAG_VIEWERS =yt_length;//接触JSONArray
JSONArray数据= NULL;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main); //为哈希映射的ListView
ArrayList的<&HashMap的LT;字符串,字符串>> DataList控件=新的ArrayList<&HashMap的LT;字符串,字符串>>(); //创建JSON解析器实例
JSONParser分析器=新JSONParser(); // URL从获取JSON字符串
JSONObject的JSON = NULL; JSON = Parser.getJSONFromUrl(URL);
尝试{
//获取联系人的数组
数据= json.getJSONArray(TAG_DATA); //通过所有联系人循环
的for(int i = 0; I< data.length();我++){
JSONObject的C = data.getJSONObject(I) //存储在变量中的每个JSON项目
字符串流光= c.getString(TAG_STREAMER);
字符串观众= c.getString(TAG_VIEWERS);
//字符串link = c.getString(); //创建新的HashMap
HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>(); //将每个子节点的HashMap键=>值
map.put(TAG_STREAMER,流光);
map.put(TAG_VIEWERS,观众);
//map.put(TAG_URL,链接); //添加HashList到ArrayList的
dataList.add(地图);
}
}赶上(JSONException E){
e.printStackTrace();
}
/ **
*更新解析JSON数据到ListView控件
* * /
ListAdapter适配器=新SimpleAdapter(这一点,DataList控件,
R.layout.list_item,
新的String [] {TAG_STREAMER,TAG_VIEWERS / * TAG_URL * /},新的INT [] {
R.id.streamer,R.id.viewers /*R.id.url*/}); setListAdapter(适配器); //选择单个ListView项
ListView控件LV = getListView(); //在选择单列表项启动新画面
lv.setOnItemClickListener(新OnItemClickListener(){ @覆盖
公共无效onItemClick(适配器视图<>母公司,观景,
INT位置,长的id){
//从选定的ListItem得到的值
字符串名称=((的TextView)view.findViewById(R.id.streamer))的getText()的toString()。
字符串viewers_count =((的TextView)view.findViewById(R.id.viewers))的getText()的toString()。
//字符串URL =((的TextView)view.findViewById(R.id.url))的getText()的toString()。 //开始新意图
在意向=新意图(getApplicationContext(),SingleMenuItemActivity.class);
in.putExtra(TAG_STREAMER,名);
in.putExtra(TAG_VIEWERS,viewers_count);
//in.putExtra(TAG_PHONE_MOBILE,URL);
startActivity(在);
}
});
}
}
我尝试使用断点,并且看到,当我把一个断点后 GetEntity
,该计划没有得到那里,因为它早崩溃,或者什么的。
这是我的任务异步
公共类ParsingTask扩展的AsyncTask<弦乐,太虚,太虚> {
JSONParser分析器=新JSONParser();保护无效doInBackground(字符串的URL ...){ ArrayList的<&HashMap的LT;字符串,字符串>> DataList控件=新的ArrayList<&HashMap的LT;字符串,字符串>>();
JSONObject的JSON = Parser.getJSONFromUrl(URL); 尝试{
//获取联系人的数组
数据= json.getJSONArray(TAG_DATA); //通过所有联系人循环
的for(int i = 0; I< data.length();我++){
JSONObject的C = data.getJSONObject(I) //存储在变量中的每个JSON项目
字符串流光= c.getString(TAG_STREAMER);
字符串观众= c.getString(TAG_VIEWERS);
//字符串link = c.getString(); //创建新的HashMap
HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>(); //将每个子节点的HashMap键=>值
map.put(TAG_STREAMER,流光);
map.put(TAG_VIEWERS,观众);
//map.put(TAG_URL,链接); //添加HashList到ArrayList的
dataList.add(地图);
}
}赶上(JSONException E){
e.printStackTrace();
} / **
*更新解析JSON数据到ListView控件
* * /
ListAdapter适配器=新SimpleAdapter(这一点,DataList控件,
R.layout.list_item,
新的String [] {TAG_STREAMER,TAG_VIEWERS / * TAG_URL * /},新的INT [] {
R.id.streamer,R.id.viewers /*R.id.url*/}); setListAdapter(适配器); 返回null;
}
保护无效onProgressUpdate(){}
保护无效onPostExecute(){}}
ListAdapter错误,似乎是在本有些不妥。这是我的版本如何切断code,它停止返回变量。对不起,我的英语不好,但我希望你理解我:)
加入我的PHP json的制造者。 MB的问题在那里?!
< PHP
mysql_connect(localhost的根,);
如果(!mysql_select_db(ololo)){
回声无法选择ololo。 mysql_error();
}
$ SQL =的mysql_query(选择流光,从pm_videos那里类='1'yt_length);
如果(!$ SQL)出口(错误 - .mysql_error(),$ tmp_q);
而($行= mysql_fetch_assoc($ sql中)){
$输出[] = $行;
}
$ JSON = json_en code($输出);
标题(内容类型:应用程序/ JSON');
打印{\\数据\\:$ {JSON}};
mysql_close();
?>
因为你在运行时,您PROGRAMM崩溃
JSON = Parser.getJSONFromUrl(URL);
在UI线程上下文。你必须使用一个
code看起来不错。唯一的问题是,
公共类ParsingTask扩展的AsyncTask<弦乐,无效的ArrayList<&HashMap的LT;字符串,字符串>>> {
JSONParser分析器=新JSONParser(); 保护无效doInBackground(字符串的URL ...){ArrayList的<&HashMap的LT;字符串,字符串>> DataList控件=新的ArrayList<&HashMap的LT;字符串,字符串>>();
JSONObject的JSON = Parser.getJSONFromUrl(URL);尝试{
//获取联系人的数组
数据= json.getJSONArray(TAG_DATA); //通过所有联系人循环
的for(int i = 0; I< data.length();我++){
JSONObject的C = data.getJSONObject(I) //存储在变量中的每个JSON项目
字符串流光= c.getString(TAG_STREAMER);
字符串观众= c.getString(TAG_VIEWERS);
//字符串link = c.getString(); //创建新的HashMap
HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>(); //将每个子节点的HashMap键=>值
map.put(TAG_STREAMER,流光);
map.put(TAG_VIEWERS,观众);
//map.put(TAG_URL,链接); //添加HashList到ArrayList的
dataList.add(地图);
}
}赶上(JSONException E){
e.printStackTrace();
}/ **
*更新解析JSON数据到ListView控件
* * /
返回DataList控件;
} 保护无效onPostExecute(ArrayList的<&HashMap的LT;字符串,字符串>> DataList控件){
ListAdapter适配器=新SimpleAdapter(AndroidJSONParsingActivity.this,DataList控件,
R.layout.list_item,
新的String [] {TAG_STREAMER,TAG_VIEWERS / * TAG_URL * /},新的INT [] {
R.id.streamer,R.id.viewers /*R.id.url*/});setListAdapter(适配器);
}
I need advice about my code.
I'm trying to parse a JSON array generated by the PHP function json_encode()
.
My json:
{"data": [{"streamer":"froggen","yt_length":"25078"},{"streamer":"wingsofdeath","yt_length":"8979"},{"streamer":"guardsmanbob","yt_length":"4790"},{"streamer":"kaostv","yt_length":"4626"},{"streamer":"kungentv","yt_length":"3883"},{"streamer":"destiny","yt_length":"3715"},{"streamer":"zekent","yt_length":"3428"},{"streamer":"athenelive","yt_length":"1673"},{"streamer":"frommaplestreet","yt_length":"1614"},{"streamer":"keyorikeys","yt_length":"1410"},{"streamer":"riotgamesturkish","yt_length":"1397"},{"streamer":"vman7","yt_length":"1022"},{"streamer":"tiensinoakuma","yt_length":"967"},{"streamer":"affenklappe","yt_length":"748"},{"streamer":"teamkeyd","yt_length":"747"},{"streamer":"lagtvmaximusblack","yt_length":"683"},{"streamer":"lolgameru","yt_length":"665"},{"streamer":"gruntartv","yt_length":"585"},{"streamer":"entenzwerg","yt_length":"579"},{"streamer":"lolgameru_cauthonpro","yt_length":"506"},{"streamer":"basickz","yt_length":"488"},{"streamer":"ilysuiteheart","yt_length":"491"},{"streamer":"kireiautumn","yt_length":"485"},{"streamer":"ultimavv","yt_length":"471"}]}
Java class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
String response = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
And my activity:
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://ololo.tv/vasa";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_STREAMER = "streamer";
private static final String TAG_VIEWERS = "yt_length";
// contacts JSONArray
JSONArray data = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser Parser = new JSONParser();
// getting JSON string from URL
JSONObject json = null;
json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.streamer)).getText().toString();
String viewers_count = ((TextView) view.findViewById(R.id.viewers)).getText().toString();
//String url = ((TextView) view.findViewById(R.id.url)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_STREAMER, name);
in.putExtra(TAG_VIEWERS, viewers_count);
//in.putExtra(TAG_PHONE_MOBILE, url);
startActivity(in);
}
});
}
}
I tried using breakpoints, and see that when I put a breakpoint after GetEntity
, the program doesn't get there because it crashed early, or something.
This my async task.
public class ParsingTask extends AsyncTask<String, Void, Void>{
JSONParser Parser = new JSONParser();
protected Void doInBackground(String... urls) {
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
JSONObject json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
return null;
}
protected void onProgressUpdate() {
}
protected void onPostExecute() {
}
}
ListAdapter error, seems like something wrong in "this". This my version how cut off code, where it stop return variables. Sorry for bad english, but i hope you understand me :)
Add my php json maker. Mb problem there?!
<?php
mysql_connect("localhost","root","");
if (!mysql_select_db("ololo")) {
echo "Unable to select ololo: " . mysql_error();
}
$sql=mysql_query("select streamer, yt_length from pm_videos where category='1'");
if(!$sql) exit("Error - ".mysql_error().", ".$tmp_q);
while($row=mysql_fetch_assoc($sql)){
$output[]=$row;
}
$json = json_encode($output);
header('Content-Type: application/json');
print "{\"data\": ${json}}";
mysql_close();
?>
You programm crashes because you are running
json = Parser.getJSONFromUrl(url);
in the UI Thread context. You have to use an AsyncTask
Code looks good. The only problem is that
public class ParsingTask extends AsyncTask<String, Void, ArrayList<HashMap<String, String>>>{
JSONParser Parser = new JSONParser();
protected Void doInBackground(String... urls) {
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
JSONObject json = Parser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
// Storing each json item in variable
String streamer = c.getString(TAG_STREAMER);
String viewers = c.getString(TAG_VIEWERS);
//String link = c.getString();
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_STREAMER, streamer);
map.put(TAG_VIEWERS, viewers);
//map.put(TAG_URL, link);
// adding HashList to ArrayList
dataList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
return dataList;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> dataList) {
ListAdapter adapter = new SimpleAdapter(AndroidJSONParsingActivity.this, dataList,
R.layout.list_item,
new String[] { TAG_STREAMER, TAG_VIEWERS /*TAG_URL*/ }, new int[] {
R.id.streamer, R.id.viewers /*R.id.url*/ });
setListAdapter(adapter);
}
这篇关于JSON解析的Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!