Retrieve data from JSON Java Android - java

i've got a problem to retrieve information by a JSON
The Raw Json is this
{"date":"{\"yesterday\":\"Wed 28\",\"today\":\"Thu
29\",\"tomorrow\":\"Fri 30\"}"
Now how i could take this Json and format in this?
{
"date":{
"yesterday":"Wed 28",
"today":"Thu 29",
"tomorrow":"Fri 30"
}
}
And then retry the date from the key?
String jsonStr = sh.makeServiceCall(url);
Log.e("RAW-JSON: ","Retrieve RAW-Json is "+jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray DATESTRING = jsonObj.getJSONArray("date");
JSONObject d = DATESTRING.getJSONObject(0);
String Ieri = d.getString("yesterday");
Log.e("DATE-JSON", "Retrieve DATE-Json is " + yesterday);
} catch (JSONException e) {
Log.e("ERROR", "Not a good result.");
e.printStackTrace();
}
}

I would strongly recommend use the library Gson to parse a JSON document, is much easier and elegant.
public static date parseJSON(String jsonArray) {
date yourDate = new date();
try {
yourDate = (gson.fromJson(jsonArray, date.class));
} catch (Exception e) {
e.printStackTrace();
}
return yourDate;
}
Then the class date is just a class with the same elements that exists in the JSON you want to read in your case:
public class date {
private String yesterday;
private String today;
private String tomorrow;
}

JSONArray DATESTRING = jsonObj.getJSONArray("date") is wrong because "date" is not an JsonArray but an JsonObject!

What you probably need to do is (assuming you want today's date):
String todaysDate = jsonObj.getJSONObject("date").getString("today");

Just simply replace \" with " to get clean json string and then parse the json to read data usig JSONObjct.
jsonStr = jsonStr.replace("\\\"", "\"");
JSONObject jsonObj = new JSONObject(jsonStr);

Related

Convert string of valid JSON to JSON object in Java, so I can index into it

I have this string:
[{"row 0":[{},{},{},{},{},{},{},{}]},{"row 1":[{},{},{},{},{},{},{},{}]},{"row 2":[{},{},{},{},{},{},{},{}]},{"row 3":[{},{},{},{},{},{},{},{}]},{"row 4":[{"column 0":"WhitePawn"},{},{},{},{},{},{},{}]},{"row 5":[{},{},{},{},{},{},{},{}]},{"row 6":[{},{},{},{},{},{},{},{}]},{"row 7":[{},{},{},{},{},{},{},{}]}]
^ it's currently a String, let's call it string.
I'm trying to convert it into JSON like so:
new JSONObject(string);
but it isn't working. How to do this in Java?
Code looks like so:
private void parseMessageRedrawBoard(String message) {
Log.d("0000: ", message);
String trimmed = message.substring(message.indexOf("["));
Log.d("1111: ", trimmed);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(trimmed);
Log.d("maybe worked...", "~");
} catch (Exception e) {
Log.d("dammit: ", e.getMessage());
}
}
You are trimming the string and turning it into an invalid JSON.
Your JSON starts with a "[" that indicates it is an array. If it starts with "{" you can assume that is an object.
So, as your JSON is an array, you can parse this exact content you mentioned with:
JSONArray jsonArray = new JSONArray(string);
And access the elements like in a List:
jsonArray.get(0);

Parse.com add JSON Object to JSON Array

My problem is simple, I'd like to add a JSONObject to a JSONArray that I store in a MongoDB database. I can easily add all types of data like Strings, Ints etc but not JSONObjects.
I do this in my code :
public void done(ParseObject lan, ParseException e) {
if(e==null){
JSONObject object = new JSONObject();
try{
object.put("PlayerName","John");
object.put("ID",514145);
lan.add("Participants",object); //nothing gets inserted
lan.add("Participants",15); //works fine
lan.add("Participants",JSONObject.null); //works fine too
}catch (JSONException error){
}
lan.increment("Number");
lan.saveInBackground();
}else{
Log.i("Parse Error","error");
}
}
But nothing appears in my db and there's no error thrown.
Do you guys have any clue on how to do that ?
Try using object.toString() instead of object.
lan.add("Participants", object.toString());
JSON:
{"Participants":["{\"PlayerName\":\"John\",\"ID\":514145}"]}
To parse this JSON try this:
JSONObject jsonObj = new JSONObject(YOUR_JSON_STRING);
// Participants
JSONArray participantsJsonArray = jsonObj.getJSONArray("Participants");
// Participant
JSONObject participanJsonObject = participantsJsonArray.getJSONObject(0);
// PlayerName
String playerName = participanJsonObject.getString("PlayerName");
// ID
String id = participanJsonObject.getInt("ID");
Hope this will help~
Convert that Json Object into String and store it in string format
lan.add("Participants",object.toString());
And when you want to use that you can easily convert it into Json Object again like this
JSONObject jObj=new JSONObject("Your Json String");

how to iterate json String

I have an array of JSON strings like:
[{
"id":"BirthDate",
"field":"BirthDate",
"type":"date",
"input":"text",
"operator":"equal",
"value":"2016/04/07"
}]
I want to be able to iterate this array and want to get its id, field, value in Java
Using the below code I got an exception
"json object must begin with {"
String rules=helper.getRules();
System.out.println("====Rulses=====:"+rules);
try {
JSONObject obj = new JSONObject(rules);
System.out.println("====obj===="+obj);
// boolean error = obj.getBoolean("error");
String id = obj.getString("id");
System.out.println("===id is===: "+id);
} catch (JSONException e){
e.printStackTrace();
}
You should instead create a JSONArray from the String and then iterate over the array. Modify your code as
String rules=helper.getRules();
System.out.println("====Rulses=====:"+rules);
try {
// create the json array from String rules
JSONArray jsonRules = new JSONArray(rules);
// iterate over the rules
for (int i=0; i<jsonRules.length();i++){
JSONObject obj = jsonRules.get(i);
System.out.println("====obj===="+obj);
String id = obj.getString("id");
System.out.println("===id is===: "+id);
}
} catch (JSONException e){
e.printStackTrace();
}
Try this parsing your rulesinto a JSONArray:
String rules = "[{\"id\":\"BirthDate\",\"field\":\"BirthDate\",\"type\":\"date\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"2016/04/07\"}]";
try {
JSONArray obj = new JSONArray(rules); // parse the array
for(int i = 0; i < obj.length(); i++){ // iterate over the array
JSONObject o = obj.getJSONObject(i);
String id = o.getString("id");
System.out.println("===id is===: " + id);
}
} catch (JSONException e){
e.printStackTrace();
}
In the JSON you gave as example you just have one element in your array.

Android data transferring with Json issue

This is my json array creating with php.
I want to know bellow json array have correct syntax.
How to get the values withing android,because my sample code get some errors.
THIS IS PHP SCRIPT FOR JSON ARRAY GENARATING
public static function getCategory($_lgtime) {
$con = JsonDataManip::connect();
$stmt = $con->prepare("select * from " . _TABLE_CATEGORY . " where lgtime > ?");
$stmt->execute(array($_lgtime));
while ($row = $stmt->fetch()) {
$jsonArray['key'] = $row['key'];
$jsonArray['name'] = $row['name'];
$jsonArray['lgtime'] = $row['lgtime'];
$json[] = $jsonArray;
}
return $json;
}
usage php :
echo json_encode(JsonDataManip::getCategory('20140129184514895'));
GENARATED JSON ARRAY
[{
"key":"1",
"name":"Category 10",
"lgtime":"20140129184514896"
},
{
"key":"2",
"name":"Category 9",
"lgtime":"20140129184514896"
},
{
"key":"3",
"name":"Category 8",
"lgtime":"20140129184514896"
}]
ANDROID JSON PARSER FUNCTION
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsnArry = new JSONObject(jsonStr);
JSONArray jsonArray = jsnArry.getJSONArray("");
for(int i=0;i<jsnArry.length();i++){
Log.d("JSON PARSE",jsonArray.getJSONObject(i).getString("name"));
//contactList[i] =
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
ERROR
01-30 08:45:53.527: W/System.err(1507): org.json.JSONException: Value {"lgtime":"20140129184514896","key":"1","name":"Category 10"} at 0 of type org.json.JSONObject cannot be converted to JSONArray
Your PHP script returns a JSON array, not a JSON object. You should update your Android code like so:
if (jsonStr != null) {
try {
JSONArray json = new JSONArray(jsonStr);
for (int i=0; i < json.length(); i++) {
Log.d("JSON PARSE", json.getJSONObject(i).getString("name"));
}
} catch (JSONException e) {
Log.w("JSON PARSE", "Failed to parse JSON!", e);
}
}
To check if your JSON string is valid, please use this link JSONLint.
As far your error is concerned for your code, it clearly states that
type org.json.JSONObject cannot be converted to JSONArray
Possible Solution (if you are using Gson)
Your response from ServiceHandler would be a string. So convert that into a JSONObject and the pass that to JSONArray.
Example
JSONObject jsonObject = new JSONObject(<responseString>);
JSONArray jsonArray = jsonObject.getJSONArray();
Else
JSONObject jsonObject = new JSONObject(<responseString>);
String key = jsonObject.getJSONObject("key");
String name = jsonObject.getJSONObject("name");
String lgtime = jsonObject.getJSONObject("lgtime");
Then you can continue with your logic in the program.
{ "employees":[
{
"firstName":"John",
"lastName":"Doe"
},
{
"firstName":"Anna",
"lastName":"Smith"
},
{
"firstName":"Peter",
"lastName":"Jones"
}
]
}
Your opening and closing braces are missing. that is not a valid json array, The above is a sample array format

How to Parse the JSON String Android

I'm trying to Parse the below JSONString
[[{"0":"
","title":" Technical Support Analyst in Noida","1":"
","Company Name":" Oracle","2":"
","Category":"Fresher","3":"
","Job Type":"Full Time","4":"
","Location":"Noida","5":"
","Job Qualification":"BE\/BTch\/Bsc\/Others","6":"
","Job Experience":"Freshers","7":"
","Job postdate":"2013-6-05","8":"
"}]]
Here My Code:
// try parse the string to a JSON object
try {
//jObj = new JSONObject(JsonString);
JSONArray ja = new JSONArray(result);
int size = ja.length();
Log.d("tag", "No of Elements " + ja.length());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Could any one help,My Code is not Working?
I want to Parse title,CompanyName,Category Etc...
You need to create JSONArray from your jsonstring.
You have JSONArray inside JSONArray and then JSONObect..
try {
JSONArray ja = new JSONArray(buffer.toString());
JSONArray innerJsonArray = ja.getJsonArray(0);
JSONObject object = innerJsonArray.getJSONObject(0);
String title = object.getString("title");
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Take a look at this Json parsing guide using native tools and Gson library that I wrote:
Json Parsing
Maybe you will find it useful.
You can download the full project from there as well to run and test it for yourself.
You need to structure your json.
There is no array named "result". What you have to do is to name every element of the json with a unique name, so as to fetch it.
such as
{"result":
["result1":["result2":{"0":"
","title":" Technical Support Analyst in Noida","1":"
","Company Name":" Oracle","2":"
","Category":"Fresher","3":"
","Job Type":"Full Time","4":"
","Location":"Noida","5":"
","Job Qualification":"BE\/BTch\/Bsc\/Others","6":"
","Job Experience":"Freshers","7":"
","Job postdate":"2013-6-05","8":"
"}]]}
You can try below code for parsing JSON
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea, Republic of"},
{"countryCode":"us","countryName":"United States"},
{"countryCode":"jp","countryName":"Japan"},
{"countryCode":"cn","countryName":"China"},
{"countryCode":"in","countryName":"India"}
]
}
parsing code
public static ArrayList<Country> ParseJson(String jsonstring) {
ArrayList<Country> arrCountries = new ArrayList<Country>();
String status;
String message = "";
try {
JSONObject json = new JSONObject(jsonstring);
status = json.getString("result");
if (status.equalsIgnoreCase("success")) {
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}
}
} catch (JSONException e) {
Log.e("JSON", "There was an error parsing the JSON", e);
}
return arrCountries;
}

Categories