mysql — передача php-файла для объекта json с использованием библиотеки залпов

привет, я использую библиотеку залпа для извлечения данных из базы данных mysql. Но не могу разобрать объект json. Это код моей основной деятельности

public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://someurl/feed.json";

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

listView = (ListView) findViewById(R.id.list);

feedItems = new ArrayList<FeedItem>();

listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);

// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getActionBar().setIcon(
new ColorDrawable(getResources().getColor(android.R.color.transparent)));

// We first check for cached request
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(URL_FEED);



if (entry != null) {
//fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

} else {
//making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});

//Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}

}

/**
* Parsing json reponse and passing the data to feed view list adapter
* */
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");

for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);

FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));

// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePic(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));

// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);

feedItems.add(item);
}

// notify data changes to list adapater
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}





@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

в приведенном выше коде переданный URL является объектом json, а структура объекта json

{
"feed": [
{
"id": 1,
"name": "National Geographic Channel",
"image": "http://api.androidhive.info/feed/img/cosmos.jpg",
"status": "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
"profilePic": "http://api.androidhive.info/feed/img/nat.jpg",
"timeStamp": "1403375851930",
"url": null
},
{
"id": 2,
"name": "TIME",
"image": "http://api.androidhive.info/feed/img/time_best.jpg",
"status": "30 years of Cirque du Soleil's best photos",
"profilePic": "http://api.androidhive.info/feed/img/time.png",
"timeStamp": "1403375851930",
"url": "http://ti.me/1qW8MLB"}
]
}

но я хочу передать файл php вместо объекта json, используемого в переменной URL_FEED. Файл php, который я использую,

<?php
define('HOST','mysql.******.in');
define('USER','someuser');
define('PASS','*****');
define('DB','somedb');

$con = mysqli_connect(HOST,USER,PASS,DB);

$sql = "select * from timeline";

$res = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('id'=>intval($row[0]),
'name'=>$row[1],
'image'=>$row[2],
'status'=>$row[3],
'profilePic'=>$row[4],
'timestamp'=>$row[5],
'url'=>$row[6]
));
}

header('Content-type: application/json');
echo json_encode(array("feed"=>$result),JSON_PRETTY_PRINT);

mysqli_close($con);

?>

и вывод моего файла php как

{
"feed": [
{
"id": 1,
"name": "helpme",
"image": "http:\/\/api.androidhive.info\/feed\/img\/cosmos.jpg",
"status": "Hello everyone",
"profilePic": "http:\/\/api.androidhive.info\/feed\/img\/nat.jpg",
"timestamp": "2015-08-21 19:11:15",
"url": "http:\/\/ti.me\/1qW8MLB"}
]
}

и здесь формат URL нарушается, это повлияет на синтаксический анализ файла.
Даже если выходной файл php, который я использовал, является объектом json, но передача его ссылки не работает. Я имею в виду, что в используемом просмотре списка ничего не отображается.
Может кто-нибудь, пожалуйста, помогите мне узнать, если файл php, который я использовал, правильный, если нет, как его можно исправить. И можем ли мы использовать файл php в переменной URL_FEED вместо объекта json.
Заранее спасибо.

-1

Решение

Все, что вам нужно сделать, это использоватьJSON_UNESCAPED_SLASHES

Измените свою линию эха на:

echo json_encode(array("feed"=>$result), JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector