使用json将多选数据从服务器发送到android?
我正在尝试在android中开发类似应用程序的测验。与4选择一起的问题应该来自服务器。我正在尝试使用json发送数据。问题或选择也可能包含数字。我尝试使用下面的json文件。它在android中运行良好。现在我的问题是我无法使用下面的JSON文件发送图像。是我的方式来发送数据正确或应该使用JSON一起使用PHP。使用json将多选数据从服务器发送到android?
file.json(JSON文件)
{"multiple":[{
"question": "In which course are you inrolled in?",
"choice1":"BIM",
"choice2":"BBA",
"choice3":"BIT",
"choice4":"BSCCSIT"
},
{
"question": "What comes after n?",
"choice1":"s",
"choice2":"t",
"choice3":"o",
"choice4":"p"
},
{
"question":"Who is 38th Prime Minister of Nepal?",
"choice1":"KP Oli",
"choice2":"Susil Koirala",
"choice3":"Sher Bahadur Deuba",
"choice4":"Prachanda"
}
]
}
MainActivity.java
package com.multiple;
import android.app.*;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import android.widget.AdapterView.*;
import android.widget.RelativeLayout;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class MainActivity extends Activity
{
private ListView listview;
private Button finishbtn;
private CheckBox check1,check2,check3,check4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<HashMap<String, String>> collect = new ArrayList<HashMap<String, String>>();
final List<HashMap<String, String>> answer = new ArrayList<HashMap<String, String>>();
listview = (ListView) findViewById(R.id.list);
finishbtn= (Button)findViewById(R.id.button);
populate p = new populate();
try {
collect = p.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
String[] str = new String[]{"first", "second", "third", "fourth", "fifth"};
int[] val = new int[]{R.id.textView1, R.id.checkBox1, R.id.checkBox2, R.id.checkBox3, R.id.checkBox4};
SimpleAdapter adapter = new SimpleAdapter(this, collect, R.layout.list, str, val);
listview.setAdapter(adapter);
finishbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
int count = listview.getCount();
Log.i("count",String.valueOf(count));
int j=0;
while(j<count)
{
RelativeLayout relLayout = (RelativeLayout) listview.getChildAt(j);
for(int i=0;i< relLayout.getChildCount();i++)
{
HashMap<String,String> value= new HashMap<String,String>();
View vi = relLayout.getChildAt(i);
if(vi instanceof CheckBox)
{
CheckBox c = (CheckBox)vi;
if(c.isChecked())
{
String ch = (String)c.getText();
Log.i("list",ch);
value.put(String.valueOf(j+1),ch);
answer.add(value);
}
}
}
j++;
}
Select select = new Select();
select.execute(answer);
}
});
}
public class populate extends AsyncTask< String, Void,List<HashMap<String,String>> >
{
public List<HashMap<String,String>> doInBackground(String... urls)
{
List<HashMap<String,String>> collect= new ArrayList<HashMap<String, String>>();
try
{
HttpClient client = new DefaultHttpClient();
HttpGet post = new HttpGet("http://192.168.10.116/file.json");
HttpResponse res= client.execute(post);
HttpEntity entity = res.getEntity();
String response = EntityUtils.toString(entity);
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = obj.optJSONArray("multiple");
Log.i("size of the array",String.valueOf(jsonArray.length()));
ArrayList<JSONObject> array = new ArrayList<JSONObject>();
for(int i=0; i < jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
array.add(jsonObject);
}
for(int i=0;i<array.size();i++){
JSONObject jsonObject = array.get(i);
String question = jsonObject.optString("question").toString();
String c1 = jsonObject.optString("choice1").toString();
String c2 = jsonObject.optString("choice2").toString();
String c3 = jsonObject.optString("choice3").toString();
String c4 = jsonObject.optString("choice4").toString();
// Log.i("asdfas",question);
// Log.i("second",c1);
// Log.i("third",c2);
// Log.i("fourth",c3);
// Log.i("fifth",c4);
HashMap<String,String> map = new HashMap<String, String>();
map.put("first",question);
map.put("second",c1);
map.put("third",c2);
map.put("fourth",c3);
map.put("fifth",c4);
collect.add(map);
}
}
catch(IOException ex){}
catch(JSONException ex){}
return collect;
}
}
}
Select.java
package com.multiple;
import android.os.AsyncTask;
import android.util.Log;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
public class Select extends AsyncTask<List<HashMap<String, String>>, Void, Void>
{
@Override
protected Void doInBackground(List<HashMap<String, String>>... answer) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.10.116/check.php");
JSONArray array = new JSONArray(answer[0]);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("forward",array.toString()));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
String result = null;
result = EntityUtils.toString(httpEntity);
Log.i("response", result);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
您的JSON似乎鳍即你可以稍微微调一下,我可以让每个选项都是一个类(带有成员变量“type”和“value”),而不是直接在该类中的字符串,你可以使用一个变量“type”,其值可以是“text”或“图片”。如果值是图片,您可以将字段“value”中的内容作为图片url并将其显示在imageview中,如果字段“type”为“text”,则可以将内容以“值“并在textView中显示它。
你所问的问题并不明显,但如果我弄清楚了,你有在JSON响应中发送图像的问题。
的问题
你不能在JSON发送任意的二进制数据,因为JSON使用某些字符的二进制可能包含诸如引号,这样才可以JSON响应内发送图像图像需要在不包含任何由JSON用于那些特殊字符
Base64是一种流行的选择,但显然不是在JSON背景下最节省空间的某种格式进行编码,你可以阅读更多关于它here
答案
图像中JSON
有可以实现的结果多种方式,而选择是应用相关的,如果你有你要在同一服务器中使用的形象,正在发送的问题,它更容易只是Base64编码,JSON结果中的图片内JSON
图像URL如果没有无光呃给你,或者你不关心额外的往返服务器,你可以发送一个URL到响应中的图像,然后使用url获取图像
为了保持简单,我建议只需使用Base64编码,所以基本上在你的PHP服务器你BASE64_ENCODE包二进制字符串中使用以下方式:
内JSON
<?php
$binaryData = file_get_contents("image.png");
$dataObject = [
"question" => "What is up?",
"image" => base64_encode($binaryData)
];
echo json_encode($dataObject);
?>
发送二进制数据,然后你的Android应用程序中你可以先阅读将图像作为字符串,然后在其上使用base64解码器和de将它编码为位图,够简单!
从JSON表示
JsonObject o = new JsonObject(responseString);
String b64String = o.get("image").getAsString();
byte[] rawData = Base64.decode(b64String.getBytes(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(rawData, 0, rawData.length);
获取二进制数据,你准备好去!
此代码尚未经过测试,但应该给你一个想法如何发送图片或只是JSON文件
内的任何这是我做的。
将图像商品储存在网络服务器上,或使用cloudinary这类服务。
在您的json文件中发送图像url。检查下面示例json中的图像标签。
[
{
_id: "561cc08cdf3d8595314dcb92",
location: "mumbai",
image: "https://s3.amazonaws.com/uifaces/faces/twitter/holdenweb/128.jpg",
address: "04250 Vernice Views, North Thaddeus port, Maryland",
mobile: "9999999999",
country_code: "91",
last_name: "Collins",
first_name: "Jarrell",
__v: 0,
active: true,
updated_date: "2015-10-13T08:27:56.878Z",
created_date: "2015-10-13T08:27:56.878Z",
id: "561cc08cdf3d8595314dcb92"
},
{
_id: "561cc08cdf3d8595314dcb93",
location: "mumbai",
image: "https://s3.amazonaws.com/uifaces/faces/twitter/aka_james/128.jpg",
address: "7639 Marianna Pike, Hills chester, New Mexico",
mobile: "9999999999",
country_code: "91",
last_name: "Nienow",
first_name: "Pedro",
__v: 0,
active: true,
updated_date: "2015-10-13T08:27:56.878Z",
created_date: "2015-10-13T08:27:56.878Z",
id: "561cc08cdf3d8595314dcb93"
}
]
让Android应用程序使用您的json中的URL从服务器下载图像。