read JSON file and display its contents - java

I have the file test.json on my Unix machine which has the data as below
{
"recordId" :10,
"recordName" : "RECORDS",
"records" : [ {
"field1" : 111,
"titleField" : 1,
"titleIDMap" : null,
"titleId" : 500,
"titleStartDate" : "2013-12-22T00:00:00.000+0000",
"titleEndDate" : "2013-12-03T00:00:00.000+0000",
"languageId" : 20
}]
}
Now I'm writing the REST jersey client to read the test.json and show the output as below
public class RestWebServiceClient {
private static String BASE_URL="https://myUrl.com";
public static void main(String[] args) {
JSONParser parser = new JSONParser();
final String auth = "mfndfkndfkdnfkdnfdkfndkfndfkndkfndzxzxzxz==";
try {
Object obj = parser.parse(new FileReader("/home/user/test.json"));
JSONObject jsonObject = (JSONObject) obj;
final String postData = "dataTobePosted";
final String postResult = postJSONData(auth, BASE_URL+"/search",postData);
System.out.println("\n============postResponse============");
System.out.println(postResult);
JSONObject issueObj = new JSONObject(postResult);
}
catch (AuthenticationException e){
System.out.println("Username or Password wrong!");
e.printStackTrace();
} catch (JSONException e) {
System.out.println("Invalid JSON output");
e.printStackTrace();
} catch (ClientHandlerException e) {
System.out.println("Error invoking REST method");
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String postJSONData(String auth, String url, String data) throws AuthenticationException, ClientHandlerException{
Client client = Client.create();
WebResource webResource = client.resource(url);
ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
.accept("application/json").post(ClientResponse.class, data);
int statusCode = response.getStatus();
if (statusCode == 401) {
throw new AuthenticationException("Invalid Username or Password");
}
return response.getEntity(String.class);
}
How do I read the test.json and display its contents?

For recordId :
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("recordId");
System.out.println(name);
For records :
List<String> list = new ArrayList<String>();
JSONArray jsonList = jsonObject.getJSONArray("records");
for (int i = 0; i < jsonList.length(); i++)
list.add(jsonList.getString(i));
Your records data will be inside list object

Related

How to Convert string to JSON Object?

I am using following code to deserailze the JSON data from Url.
But My Error is:Value {"InvoiceNo":18} of type java.lang.String cannot be converted to JSONObject.My Json Like: "{\"InvoiceNo\":18}" Please Any one Help me.
private class LongOperation extends AsyncTask{
#Override
protected Object doInBackground(Object[] params) {
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(
"http://192.168.1.2/Json/api/test"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String responseText = null;
try {
responseText = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject json = new JSONObject(responseText); // **Error on this line**
Iterator<String> keys = json.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = null;
try {
value = json.getString(key);
Toast.makeText(Billing.this, value + "",
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
textInvoice.setText(value.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("responseText", responseText);
return null;
}
}
Your String should not contain the character "\". If so, this is the cause of your problem.

Json parsing as logical workout

Before, i should say, my English is very bad. İm sorry for it.
i parsing wanna Json output, in my android prject. my json file is with url.
it is like there
{
"urun": [
{
"ID": "1011245",
"name": "Jeanne Darc-Elbise-jdje57942xl",
"name_eng": "Jeanne Darc-Dress-jdje57942xl",
"catID": "142",
"tedarikciCode": "jdje57942xl",
"markaID": "30",
"data1": "4",
"resim": "var/30/jdje57942xl/siyah_1_jdje57942xl.jpg",
"resim2": "var/30/jdje57942xl/siyah_2_jdje57942xl.jpg",
"resim3": "var/30/jdje57942xl/siyah_3_jdje57942xl.jpg",
"fiyat": "28",
"ozellik1detay": "44-50"
}
]
}
my parser class is
public class JsonParsers
{
final String TAG = "JsonParsers.java";
static InputStream is =null;
static JSONObject jObj=null;
static String ParserJson=null;
public JsonParsers(String yourJsonStringUrl) {
}
public JsonParsers() {
super();
}
public String getJsonUrl(String url) throws IOException {
try{
DefaultHttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost = new HttpPost(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,"iso-8859-1"),8);
StringBuilder sb= new StringBuilder();
String line = "";
while ((line=reader.readLine())!=null)
{
sb.append(line+"\n");
//Log.e("çıktı:",line);
}
is.close();
ParserJson = sb.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
try {
jObj=new JSONObject(ParserJson);
}
catch (JSONException e) {
e.printStackTrace();
}
return ParserJson;
}
}
My asyncTask Class is
private class AsyncTaskParseJSonIncludes extends AsyncTask<String, String, String> {
final String TAG = "MainActivity.java";
JSONArray dataJsonArr = null;
String ObjectStr;
protected String doInBackground(String... path) {
try{
try{
JsonParsers parser = new JsonParsers();
//Json = parser.getJsonUrl(JsonPath);
ObjectStr=parser.getJsonUrl(JsonPath);
JSONObject Json= new JSONObject(ObjectStr);
dataJsonArr=Json.getJSONArray("urun");
for(int i=0;i<dataJsonArr.length();i++)
{
JSONObject c = dataJsonArr.getJSONObject(i);
// Log.e("Deneme", c.getString("name"));
ID.add(Integer.valueOf(c.getString("ID")));
name.add(c.getString("name"));
name_eng.add(c.getString("name_eng"));
//name_py.add(c.getString("name_py"));
CatID.add(Integer.valueOf(c.getString("CatID")));
tedarikciCode.add(c.getString("tedarikciCode"));
markaID.add(Integer.valueOf(c.getString("markaID")));
data1.add(Integer.valueOf(c.getString("data1")));
resimmmm.add(c.getString("resim"));
resim2.add(c.getString("resim2"));
resim3.add(c.getString("resim3"));
fiyat.add(Integer.valueOf(c.getString("fiyat")));
ozellik1detay.add(c.getString("ozellik1detay"));
// ozellik2detay.add(c.getString("ozellik2detay"));
}
for(int i=0;i<name.size();i++) {
Log.e("Deneme", name.get(i));
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {}
/////////////////////////////////////////////////////////
}
it is in normaly working but it is not returned json values.
i check the parser class for stream of data, it is fixed.
But it is only first value returned, other datas don't returned.
i don't understand it logical problem. when someone help me for fix my code i very funny. Thanks.
name_eng.add().
where was the name_eng defined?
CatID to catID.
right:
Try{A}catch{}
Try{B}catch{}
Try{C}catch{}
wrong:
Try{A;B;C}catch{}
Try GsonRequest, it's very simple to parse JSON, nice example of use it you have there: USE GsonRequest

How to get text from JSON without [" "]

How do I get text from json without [" "] only text, in Android project?
this is my json from url {"code":200,"lang":"en-ru","text":["Better late than never"]}
i need get text "text":["Better late than never"] without [" "] only text: Better late than never
myclass MAINACTIVITY
public class MainActivity extends Activity {
JSONParser jsonparser = new JSONParser();
TextView tv;
String ab;
JSONObject jobj = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tvResult);
new retrievedata().execute();
}
class retrievedata extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
jobj = jsonparser.makeHttpRequest("https://translate.yandex.net/api/v1.5/tr.json/translate?key=YOURAPIKEY&text=Better%20late%20than%20never&lang=ru");
// check your log for json response
Log.d("Login attempt", jobj.toString());
ab = jobj.optString("text");
return ab;
}
protected void onPostExecute(String ab){
tv.setText(ab);
}
}
}
MY JSONPARSER CLASS
public class JSONParser {
static InputStream is = null;
static JSONObject jobj = null;
static String json = "";
public JSONParser(){
}
public JSONObject makeHttpRequest(String url){
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
HttpResponse httpresponse = httpclient.execute(httppost);
HttpEntity httpentity = httpresponse.getEntity();
is = httpentity.getContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while((line = reader.readLine())!=null){
sb.append(line+"\n");
}
is.close();
json = sb.toString();
try {
jobj = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jobj;
}
}
This is a problem with people who aren't that familiar with JSON structure. When I am looking at JSON, I find it easier to pretty-print it, because it makes the structure very clear. In the case of your JSON: {"code":200,"lang":"en-ru","text":["Better late than never"]}, it becomes:
{
"code": 200,
"lang": "en-ru",
"text": [
"Better late than never"
]
}
The error in your code is that you are trying to parse the "text" key of the dictionary as a String, when it is instead, an array containing a string. To correct, replace this
ab = jobj.optString("text");
return ab;
with
JSONArray ar = jobj.optJSONArray("text");
if (ar != null) {
return ar.optString(0);
}
From your json from url {"code":200,"lang":"en-ru","text":["Better late than never"]}
Try this...
Yout JSON structure
{
"code": 200,
"lang": "en-ru",
"text": [
"Better late than never"
]
}
You can get your output using below..
try {
JSONObject jsonObj = new JSONObject(json);
String code = jsonObj.getString("code");
String lang = jsonObj.getString("lang");
JSONArray text = jsonObj.getJSONArray("text");
Log.e("output", "code:" + code + "\nlang:" + lang + "\ntext"
+ text.getString(0));
} catch (Exception e) {
e.printStackTrace();
}

Weird json nullpointer

I've such a weird error:
Im trying to parse json objects from a url. Which works perfect for example this is the json data:
{"type":"result","rid":"djoezradio",
"data":[{
"title":"Webradio",
"song":"Test",
"track":{
"artist":"Test",
"title":"Test",
"album":"",
"Test":422,
"id":423,
"playlist":{
"id":14,"title":"reggae"
},
"imageurl":"http:\/\/example.com\/static\/example\/covers\/nocover.png"},
"bitrate":"128 Kbps",
"server":"Online","autodj":"Online","source":"Yes","offline":false","listeners":1,
"maxlisteners":500,"reseller":0,"serverstate":true,"sourcestate":true,
"sourceconn":true,"date":"Dec 14, 2013",
"time":"02:13 PM","url":"http:\/\/example.com\/"}]}
This is my code:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://example.com"));
HttpResponse response;
try {
response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
String line = "";
while ((line = in.readLine()) != null) {
JSONObject jObject = new JSONObject(line);
String temp = jObject.getString("imageurl");
Log.e("rid",temp);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When i do getString("playlist") for example, it just works well, it will return id:14 etc.
The ONLY thing which doesn't work is the object imageurl...
When i want to parse this, it just returns null, while its just there!
Any ideas?
Is there some reason? Its becouse its a .jpeg?
Pleas share, im really stuck.
Try this.
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://example.com"));
HttpResponse response;
try {
response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String line;
while((line=in.readLine())!=null)
{
builder.append(line);
}
String JSONdata = builder.toString();
Log.i("JsonData",JSONdata);
JSONObject jObject = new JSONObject(JSONdata);
String temp = jObject.getString("imageurl");
Log.e("rid",temp);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT
JSONObject jObject = new JSONObject(JSONdata);
JSONArray jdata = jObject.getJSONArray("data");
JSONObject job = jdata.getJSONObject(0);
JSONObject jObjt = job.getJSONObject("track");
String temp = jObjt.getString("imageurl");
Log.e("rid",temp);

sort JSONArray without Gson, Jackson, etc

In my app, the class below receives a JSONArray and use its data to populate a ListView. I want the fields in this ListView to appear in an Alphabetical order. So I want to sort my JSONArray before using its data.
I've saw some topics suggesting to use GSON or Jackson, but I'm trying to do this in a simpler way. I don't understand well these libraries and did't find what I need in their tutorials.
An example of the JSON:
{"0":["1","Alimentos e Bebidas","Y"],"1":["6","Beleza e Cosm\u00e9ticos","Y"],"2":
["11","Cama, Mesa e Banho","Y"],"3":["3","CDs, DVDs e Games","Y"],"4":["2","Convites
e Cortesias","Y"],"5":["23","Cursos","Y"],"6":["8","Eletr\u00f4nicos","Y"],"7":
["16","Esporte e Lazer","Y"],"8":["14","Inform\u00e1tica e Acess\u00f3rios","Y"],
"9":["10","Limpeza","Y"],"10":["4","Livros","Y"],"11":["21","Livros no Sebo","Y"],
"12":["5","Outros","Y"],"13":["12","Roupas e Acess\u00f3rios","Y"]}
The class' method where I populate the list and wait for user:
public void proccess(){
listview = (ListView) findViewById(R.id.include3);
int qtdCategorias = json.length();
categorias = new String[qtdCategorias];
itens = new ArrayList<ItemListView>();
for (int i=0; i<qtdCategorias; i++){
c = json.optJSONArray(i);
String nomeCategoria = null;
try {
nomeCategoria = c.getString(1); //A consulta SQL do php retorna somente categorias habilitadas
} catch (JSONException e) {
Log.e("CategoriasShoppingActivity", e.toString());
e.printStackTrace();
}
categorias[i] = nomeCategoria;
//ItemListView item = new ItemListView(nomeCategoria);
//itens.add(item);
}
Arrays.sort(categorias);
for (int i=0; i<qtdCategorias; i++){
ItemListView item = new ItemListView(categorias[i]);
itens.add(item);
}
adapterListView = new AdapterListView(this, itens);
listview.setAdapter(adapterListView);
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
c = json.optJSONArray(position);
String name = null;
String idt = null;
try {
name = c.getString(1);
idt = c.getString(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent in = new Intent(getApplicationContext(), ProdutosActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_ID, idt);
startActivity(in);
}
});
}
[EDIT]
To request data from server, I use this JSONParser class ():
public class JSONParser{
static InputStream is = null;
static JSONArray jArr = null;
static JSONStringer jArrString = null;
static String json = "";
private static Context context;
private ProgressDialog loader;
// static HttpEntity httpEntity = null;
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// json = EntityUtils.toString(httpEntity);
// HttpEntity httpEntity2 = httpEntity;
json = EntityUtils.toString(httpEntity);
// is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("JSONParser", "IOException "+e.toString());
e.printStackTrace();
}
try {
char[] c = new char[json.length()];
json.getChars(0, json.length(), c, 0);
int i = 0;
while (c[i] == '\u00EF' || c[i] == '\u00BB' || c[i] == '\u00BF') { // remove
// utf-8
// BOM
i++;
}
json = json.substring(i);
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
JSONObject json_data = new JSONObject(json);
JSONArray hashMap_names = json_data.names();
JSONArray hashMap_names2 = new JSONArray();
Map hashMap = new HashMap(json_data.length());
for (int i = 0; i != hashMap_names.length(); i++) {
hashMap.put(String.valueOf(i), json_data.get(String.valueOf(i)));
hashMap_names2.put(String.valueOf(i));
}
JSONObject hashMap_obj = new JSONObject(hashMap);
jArr = hashMap_obj.toJSONArray(hashMap_names2);
// jArr = new JSONArray(json);
Log.e("JSON Parser", "succesful parsing data " + jArr.toString());
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
jArr = null;
}
// return JSON String
return jArr;
}
And here I receive the JSON in my class
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == 1){
if (resultCode == RESULT_OK){
try {
json = new JSONArray(data.getStringExtra(TAG_JSON));
Log.e("CategoriasShoppingActivity", "JSON: "+json);
} catch (JSONException e) {
e.printStackTrace();
}
proccess();
}else{ // resultCode == RESULT_CANCELED
Log.d("CategoriasJogarActivity", "AsyncTaskActicity retornou RESULT_CANCELED");
finish();
}
}
}
If you have access to server-side code, it will be easier to sort the list there. If not, your only way to do so, is to parse it to ArrayList and simply sort it using any known algorithm.
Why don't you sort it before serializing ? Use Comparator interface and sort it using Collections.sort. Pass the comparator as as the parameter when sorting

Categories