This is what the JSON looks like:
[{
"pmid": "2",
"name": " MANAGEMENT",
"result": "1",
"properties": [
{
"prop_id": "32",
"prop_name": "Bonneville",
"address": "122 Lakeshore",
"city": "Ripley",
"state": "OH",
"zip": "11454",
"lat": "41.123",
"long": "-85.5034"
}
]
}]
I am trying to parse it with the following Java code in Android:
JSONObject jObj = null;
try {
jObj = new JSONObject(jsonStr);
// We get weather info (This is an array)
JSONArray jArr = jObj.getJSONArray("properties");
// We use only the first value
//JSONObject JSONWeather = jArr.getJSONObject(0);
JSONObject c = jArr.getJSONObject(0);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String phone = c.getString(TAG_PHONE);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
I am not getting any results though. How can I successfully parse this JSON? I'm using Android Studio.
Also, if there were multiple pieces to the array, how could we make sure each one of them is printed out?
Your JSON string start with JSONArray.
Here sample code, try it.
JSONArray mJsonArray = new JSONArray(jsonStr);
JSONObject mJsonObject = mJsonArray.getJSONObject(0);
String pmid = mJsonObject.getString("pmid");
String name = mJsonObject.getString("name");
String result = mJsonObject.getString("result");
JSONArray mJsonArrayProperty = mJsonObject.getJSONArray("properties");
for (int i = 0; i < mJsonArrayProperty.length(); i++) {
JSONObject mJsonObjectProperty = mJsonArrayProperty.getJSONObject(i);
String prop_id = mJsonObjectProperty.getString("prop_id");
String prop_name = mJsonObjectProperty.getString("prop_name");
String address = mJsonObjectProperty.getString("address");
String city = mJsonObjectProperty.getString("city");
String state = mJsonObjectProperty.getString("state");
String zip = mJsonObjectProperty.getString("zip");
String lat = mJsonObjectProperty.getString("lat");
String lon = mJsonObjectProperty.getString("long");
}
Check Android JSON Parsing Tutorial
As in posted json String jsonStr is JSONArray of JSONObeject's instead of JOSNObject of JSONArray.
So convert jsonStr String to JSONArray:
JSONArray jArray = new JSONArray(jsonStr);
JSONObject c = jArray.getJSONObject(0);
// get properties JSONArray from c
JSONArray jArrProperties = c.getJSONArray("properties");
JSONObject jsonObject = jArrProperties.getJSONObject(0);
Here is complete example with resolution.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
public static void main(String[] args)
{
JSONObject jObj = null;
try {
String jsonStr = "[{\"pmid\":\"2\",\"name\":\" MANAGEMENT\",\"result\":\"1\",\"properties\":[{\"prop_id\":\"32\",\"prop_name\":\"Bonneville\",\"address\":\"122 Lakeshore\",\"city\":\"Ripley\",\"state\":\"OH\",\"zip\":\"11454\",\"lat\":\"41.123\",\"long\":\"-85.5034\"}]}]";
jsonStr = jsonStr.substring(1, jsonStr.length()-1);
System.out.println(jsonStr);
jObj = new JSONObject(jsonStr);
System.out.println("pmid="+jObj.get("pmid"));
System.out.println("name="+jObj.get("name"));
System.out.println("result="+jObj.get("result"));
JSONArray jArr = jObj.getJSONArray("properties");
JSONObject c = jArr.getJSONObject(0);
System.out.println("prop_id=="+c.get("prop_id"));
System.out.println("prop_name=="+c.get("prop_name"));
System.out.println("address=="+c.get("address"));
System.out.println("city=="+c.get("city"));
System.out.println("state=="+c.get("state"));
System.out.println("zip=="+c.get("zip"));
System.out.println("lat=="+c.get("lat"));
System.out.println("long=="+c.get("long"));
} catch (JSONException e)
{
e.printStackTrace();
}
}
}
in this exammple details object contain j son data
JSONObject details = mJSONParser.doInBackground(); //json object
Child_Registration_StaticData deta=new Child_Registration_StaticData();
try
{
deta.UniqueID = details.getString("UniqueID");
deta.Nameofchild= details.getString("Nameofchild");
deta.FatherName= details.getString("FatherName");
deta.DOB= details.getString("DOB");
child_name.setText(deta.Nameofchild);
father_name.setText(deta.FatherName);
dateof_birth.setText(deta.FatherName);
}
Your root object is a JSON array [], not a JSON object {} there. So, you need
jObj = new JSONArray(jsonStr);
jObj = jObj.getJSONObject(0);
The rest of your code will now work fine treating jObj as a JSONObject. The concept here is exactly the same as what you're doing for your properties JSON array.
use this
try {
JSONArray array0 = new JSONArray(Sample);
JSONObject object0 = array0.getJSONObject(0);
JSONArray array1 = object0.getJSONArray("properties");
JSONObject object1 = array1.getJSONObject(0);
String name = object1.getString("prop_name");
} catch (JSONException e) {
e.printStackTrace();
}
Related
For the below Json payload I'am trying to get the first array element of email_address.
However using the below code I get email address but with the array bracket and quotes like: ["test#test.com"].
I need only the email address text. First element array.
Payload:
{
"valid":{
"email_addresses":[
"testauto#test.com"
]
}
}
Code:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(jsonfilepath));
JSONObject jsonObjects = (JSONObject) parser.parse(jsonObject.get("valid").toString());
String email = jsonObjects.get("email_addresses").toString();
System.out.println("Email address:"+email);
Maybe this unitTest could help you
#Test
public void test() throws JSONException, FileNotFoundException {
JSONObject json = new JSONObject(new JSONTokener(new FileInputStream(new File(jsonfilepath))));
JSONObject valid = (JSONObject) json.get("valid");
Object emailAdresses = valid.get("email_addresses");
if (emailAdresses instanceof JSONArray) {
JSONArray emailAdressArray = (JSONArray) emailAdresses;
Object firstEmailAdress = emailAdressArray.get(0);
System.out.println(firstEmailAdress.toString());
}
}
You could use JSONArray to get the array values:
JSONArray emailAddresses = (JSONArray) jsonObjects.get("email_addresses");
String email = emailAddresses.getJSONObject(0).toString()
System.out.println("Email address: " + email);
Even though I strongly encourage using gson to parse json instead of doing this way, it makes life easier.
I have some JSON that is returned as follows:
[{"on_arrival_inst":"Ok","order_inst":"Ok","finished_inst":"Ok"},{"on_arrival_inst":"Arrive","order_inst":"Order","finished_inst":"Finished"}]
I am trying to split these into two arrays and get the strings out as follows:
jsonResultsObject = new JSONObject(result);
jsonArray = jsonResultsObject.getJSONArray("");
int count = 0;
String onArrive, onReady, onFinished;
while (count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
count++;
}
However the code never goes into the loop, as the array is not getting populated from the JSONObject?
your result is JSONArray not JSONObject. That's why you must convert it to array not to object.
use
jsonResultsArray = new JSONArray(result);
instead of
jsonResultsObject = new JSONObject(result);
and the full code will be
jsonResultsArray = new JSONArray(result);
int count = 0;
String onArrive, onReady, onFinished;
while (count<jsonResultsArray.length()){
JSONObject JO = jsonResultsArray.getJSONObject(count);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
count++;
}
#BigJimmyJones
The fact of that the code does not enter the loop is just because your JSONArray does not have a key named "" but it contains JSONObjects instead. Objects and arrays in JSON have different annotations. See: JSON Reference Website
So your code should be :
jsonResultsObject = new JSONObject(result);
String onArrive, onReady, onFinished;
for (int i=0;i<jsonArray.length();i++){
JSONObject JO = jsonArray.getJSONObject(i);
onArrive = JO.getString("on_arrival_inst");
onReady = JO.getString("order_inst");
onFinished = JO.getString("finished_inst");
System.out.println(onArrive);
System.out.println(onReady);
System.out.println(onFinished);
}
And also ensure that your code is inside a try - catch block to catch JSONException
JSONObject jsonObj = new JSONObject("string");
jsonObj.toString();
"employees":[{"firstname":"stack","lastname":"overflow"}, {"firstname":"Happy","lastname":"Coding"}]
How can I append:
{"firstname":"Gloomy","lastname":"Sunday"}
to above json object
I want to get
"employees":[{"firstname":"stack","lastname":"overflow"}, {"firstname":"Happy","lastname":"Coding"}, {"firstname":"Gloomy","lastname":"Sunday"}]
upon jsonObj.toString();
Please do research this yourself first, this website is not here to do your computer science homework for you. Just cause I need some rep...
public class ex{
void example(){
try{
JSONObject jobj = new JSONObject("[{firstname:stack,lastname:overflow}]");
JSONObject jobj2 = new JSONObject("[{firstname:Happy,lastname:Coding}]");
JSONArray jarray = new JSONArray();
jarray.put(jobj);
jarray.put(jobj2);
}catch(JSONException e){
e.printStackTrace();
}
}
}
JSONObject jsonObj = new JSONObject();
JSONObject jo1 = new JSONObject("{"firstname":"Gloomy","lastname":"Sunday"}");
jsonObj.append("employees", jo1);
I want to read this json in a servlet
{
"text" : "ABC",
"msg" : "9551667858",
"all":[
{"name":"one"},
{"name":"two"}
],
"obj":{
"firstname":"John",
"lastname":"Doe"
}
}
Now i want to get this values to separately to string,jsonarray and json object
this is how i do that
PrintWriter out = response.getWriter();
try {
String newObj = request.getParameter("text");;
JSONObject jObj = new JSONObject(request.getParameter("obj"));
JSONArray jArray=new JSONArray(request.getParameter("all"));
out.print(newObj);
} catch (Exception e) {
e.printStackTrace();
out.write(e.toString());
}
response.setContentType("application/json");
your code is partially correct.String newObj = request.getParameter("jsondata"); is correct. Then you have to create the jObj from newObj string.
String jsonString = <your json String>
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject allObj = jsonObj.getJSONObject("obj");
JSONArray allArray = jsonObj.getJSONArray("all");
First read the data from request object :-
String jsonStr = request.getParameter("jsondata");
Use org.json library to parse it and create JsonObject :-
JSONObject jsonObj = new JSONObject(jsonStr );
Now, use this object to get your values :-
String id = jsonObj.getString("text");
You can see complete example here :-
How to parse Json in java
if your String data like ,
{
"text" : "ABC",
"msg" : "9551667858",
"all":[
{"name":"one"},
{"name":"two"}
],
"obj":{
"firstname":"John",
"lastname":"Doe"
}
}
and It can get like,
String jsonData = request.getParameter("jsondata");
Parse to JSONObject is.
JSONObject jsonObject = new JSONObject(jsonData); // put "String"
You can get JSONArray like,
JSONArray jsonArray = jsonObject.getJSONArray("all");
good luck
My String array has the following output each time it iterates through the loop
apple
orange
I want to convert my string array output to json format/jsonarray. I tried but it gives output as
{"fruits",apple}
{"fruits",orange}
I want my output as
{"fruits": [
{
"1": "apple"
}
{
"2": "orange"
}
I tried the below code
String[] strArray = new String[] {newString};
JSONObject json=new JSONObject();
//json.put("fruits", newString);
//System.out.println(json);
for(int i=0;i<strArray.length;i++)
{
System.out.print(strArray[i]+"\t");
json.put("",strArray[i]);
}
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
for(int i=0;i<strArray.length;i++)
{
JSONObject fruit = new JSONObject();
fruit.put(""+i,strArray[i]);
array.put(fruit);
}
obj.put("Fruits",array);
System.Out.Println(obj.toString(2));
Try below code :-
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("key", "value");
String jsonString = jsonObject.toString();
I hope this will work for you.