Convert String to JSON Array from Web Request - java

i wanted to know how I can convert this string here to an array:
[{"title":"test","birth":"20.05"},{"title":"test","birth":"13.05"},{"title":"test","birth":"13.06"},{"title":"test","birth":"23.06"},{"title":"test","birth":"01.12"},{"title":"test","birth":"01.06"}]
I already found this here:
JSONObject jsnobject = new JSONObject(readlocationFeed);
JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
But if I try to make the object I always get null. And here:
JSONArray jsonArray = jsnobject.getJSONArray("locations");
I don't know what I should enter as "locations". Should I enter "[]" ?
Thanks really much for help!
Daniel

I don't know what I should enter as "locations". Should I enter "[]" ?
Nothing readlocationFeed is already a JSONArray. You just need
JSONArray jsonArray = new JSONArray(readlocationFeed);
without
JSONObject jsnobject = new JSONObject(readlocationFeed);
JSONArray jsonArray = jsnobject.getJSONArray("locations");

Shouldn't it be the other way around?
JSONArray jsnArray = new JSONArray(readlocationFeed);
Anyway I suggest you should use GSON for this kind of problem:
Gson gson = new Gson();
MyClass[] arr = gson.fromJson(str, MyClass[].class);
class MyClass{
double birth;
String title;
}

Related

Need to get JSONObjects from this

This is my URL "http://182.18.161.240:7070/sfaweb-1.1.015/get/retailers/dl-0004/2"
I was able to download the data through volley, but while parsing I'm not able to retrieve anything from this. Help would be deeply appreciated.
Response is nothing but the downloaded data.
JSONObject jsonObject=new JSONObject(response);
for(int i=0;i<jsonObject.length();i++) {
//JSONObject jsonObject1=jsonArray.getJSONObject(i);
String rtrname=jsonObject.getString("rtrname").toString();
String ctgname=jsonObject.getString("ctgname").toString();
String rtrphoneno=jsonObject.getString("rtrphoneno").toString();
str+= "\n rtrname:"+rtrname+"\n ctgname:"+ctgname+"\n rtrphoneno:" +rtrphoneno+"\n";
boolean isInserted = database.insertData(rtrname,ctgname,rtrphoneno);
}
What am I missing in this?
I have been stuck on this for quite some time, so please help me. I'm kinda new to this.
The response you are getting is an array so you should put it in an array:
JSONArray jsonArray = new JSONArray(response);
Try Below Code,
JSONArray jsonArray = new JSONArray(response);
for(int i=0;i < jsonArray.length(); i++)
{
JSONObject jsonObject= jsonArray.getJSONObject(i);
//JSONObject jsonObject1=jsonArray.getJSONObject(i);
String rtrname=jsonObject.getString("rtrname").toString();
String ctgname=jsonObject.getString("ctgname").toString();
String rtrphoneno=jsonObject.getString("rtrphoneno").toString();
str+= "\n rtrname:"+rtrname+"\n ctgname:"+ctgname+"\n rtrphoneno:" +rtrphoneno+"\n";
boolean isInserted = database.insertData(rtrname,ctgname,rtrphoneno);
}

Extract Fields from a Json String in Java

I am trying to extract the ids from each company_id from the following Json String
String test = ["{\"company_id\":4100,\"data\":{\"drm_user_id\":572901936637129135,\"direct_status_id\":0,\"direct_optin_date\":0,\"direct_first_optin_date\":0,\"direct_last_optin_date\":0,\"direct_optout_date\":0,\"direct_last_form_date\":0,\"direct_last_form_id\":0,\"direct_last_promo_id\":0,\"anon_status_id\":600,\"anon_optin_date\":1446132360498,\"anon_first_optin_date\":1446132360498,\"anon_last_optin_date\":1446132360498,\"anon_optout_date\":0,\"anon_last_form_date\":1446132360498,\"anon_last_form_id\":101,\"anon_last_promo_id\":1002003,\"last_registration_date\":1446132360498,\"mp_status_id\":600,\"mp_control_state\":-1,\"mp_match_date\":0,\"mp_vs_version\":0,\"mp_initial_value_segment\":0,\"mp_id\":0,\"conversion_last_form_date\":0,\"conversion_last_form_id\":0,\"conversion_last_promo_id\":-1,\"last_message_date\":1446132368928,\"cg_version\":0,\"cg_version_date\":0,\"num_anon_messages_global\":0,\"num_anon_messages_global_date\":0,\"reg_creator_id\":576,\"reg_form_id\":101,\"reg_method_id\":1,\"reg_creator_type_id\":1},\"personal_data\":{\"version\":0,\"personal_data\":\"{}\",\"mdc_data\":{\"version\":0},\"custom_data\":\"{}\"},\"category_data\":{},\"campaignImpressions\":{},\"journeyStartDate\":0}","{\"company_id\":4045,\"data\":{\"drm_user_id\":572901936637129135,\"direct_status_id\":0,\"direct_optin_date\":0,\"direct_first_optin_date\":0,\"direct_last_optin_date\":0,\"direct_optout_date\":0,\"direct_last_form_date\":0,\"direct_last_form_id\":0,\"direct_last_promo_id\":0,\"anon_status_id\":600,\"anon_optin_date\":1446132360498,\"anon_first_optin_date\":1446132360498,\"anon_last_optin_date\":1446132360498,\"anon_optout_date\":0,\"anon_last_form_date\":1446132360498,\"anon_last_form_id\":101,\"anon_last_promo_id\":1002003,\"last_registration_date\":1446132360498,\"mp_status_id\":600,\"mp_control_state\":-1,\"mp_match_date\":0,\"mp_vs_version\":0,\"mp_initial_value_segment\":0,\"mp_id\":0,\"conversion_last_form_date\":0,\"conversion_last_form_id\":0,\"conversion_last_promo_id\":-1,\"last_message_date\":1446132368928,\"cg_version\":0,\"cg_version_date\":0,\"num_anon_messages_global\":0,\"num_anon_messages_global_date\":0,\"reg_creator_id\":576,\"reg_form_id\":101,\"reg_method_id\":1,\"reg_creator_type_id\":1},\"personal_data\":{\"version\":0,\"personal_data\":\"{}\",\"mdc_data\":{\"version\":0},\"custom_data\":\"{}\"},\"category_data\":{},\"campaignImpressions\":{},\"journeyStartDate\":0}","{\"company_id\":2979,\"data\":{\"drm_user_id\":572901936637129135,\"direct_status_id\":0,\"direct_optin_date\":0,\"direct_first_optin_date\":0,\"direct_last_optin_date\":0,\"direct_optout_date\":0,\"direct_last_form_date\":0,\"direct_last_form_id\":0,\"direct_last_promo_id\":0,\"anon_status_id\":600,\"anon_optin_date\":1446132360498,\"anon_first_optin_date\":1446132360498,\"anon_last_optin_date\":1446132360498,\"anon_optout_date\":0,\"anon_last_form_date\":1446132360498,\"anon_last_form_id\":101,\"anon_last_promo_id\":1002003,\"last_registration_date\":1446132360498,\"mp_status_id\":600,\"mp_control_state\":-1,\"mp_match_date\":0,\"mp_vs_version\":0,\"mp_initial_value_segment\":0,\"mp_id\":0,\"conversion_last_form_date\":0,\"conversion_last_form_id\":0,\"conversion_last_promo_id\":-1,\"last_message_date\":1446132368928,\"cg_version\":0,\"cg_version_date\":0,\"num_anon_messages_global\":0,\"num_anon_messages_global_date\":0,\"reg_creator_id\":576,\"reg_form_id\":101,\"reg_method_id\":1,\"reg_creator_type_id\":1},\"personal_data\":{\"version\":0,\"personal_data\":\"{}\",\"mdc_data\":{\"version\":0},\"custom_data\":\"{}\"},\"category_data\":{},\"campaignImpressions\":{},\"journeyStartDate\":0}"]
I am very new to working with Json. This is what I have so far:
JSONObject jsonObject = new JSONObject(test);
JSONObject newJSON = jsonObject.getJSONObject("company_id");
System.out.println(newJSON.toString());
jsonObject = new JSONObject(newJSON.toString());
I am stuck here because I honestly do not know how would I extract the company_id.
Thank you for your time and patience.
String test = ["{\"company_id\":4100,\"data\":{\"drm_user_id\":572901936637129135,\"direct_status_id\":0,\"direct_optin_date\":0,\"direct_first_optin_date\":0,\"direct_last_optin_date\":0,\"direct_optout_date\":0,\"direct_last_form_date\":0,\"direct_last_form_id\":0,\"direct_last_promo_id\":0,\"anon_status_id\":600,\"anon_optin_date\":1446132360498,\"anon_first_optin_date\":1446132360498,\"anon_last_optin_date\":1446132360498,\"anon_optout_date\":0,\"anon_last_form_date\":1446132360498,\"anon_last_form_id\":101,\"anon_last_promo_id\":1002003,\"last_registration_date\":1446132360498,\"mp_status_id\":600,\"mp_control_state\":-1,\"mp_match_date\":0,\"mp_vs_version\":0,\"mp_initial_value_segment\":0,\"mp_id\":0,\"conversion_last_form_date\":0,\"conversion_last_form_id\":0,\"conversion_last_promo_id\":-1,\"last_message_date\":1446132368928,\"cg_version\":0,\"cg_version_date\":0,\"num_anon_messages_global\":0,\"num_anon_messages_global_date\":0,\"reg_creator_id\":576,\"reg_form_id\":101,\"reg_method_id\":1,\"reg_creator_type_id\":1},\"personal_data\":{\"version\":0,\"personal_data\":\"{}\",\"mdc_data\":{\"version\":0},\"custom_data\":\"{}\"},\"category_data\":{},\"campaignImpressions\":{},\"journeyStartDate\":0}","{\"company_id\":4045,\"data\":{\"drm_user_id\":572901936637129135,\"direct_status_id\":0,\"direct_optin_date\":0,\"direct_first_optin_date\":0,\"direct_last_optin_date\":0,\"direct_optout_date\":0,\"direct_last_form_date\":0,\"direct_last_form_id\":0,\"direct_last_promo_id\":0,\"anon_status_id\":600,\"anon_optin_date\":1446132360498,\"anon_first_optin_date\":1446132360498,\"anon_last_optin_date\":1446132360498,\"anon_optout_date\":0,\"anon_last_form_date\":1446132360498,\"anon_last_form_id\":101,\"anon_last_promo_id\":1002003,\"last_registration_date\":1446132360498,\"mp_status_id\":600,\"mp_control_state\":-1,\"mp_match_date\":0,\"mp_vs_version\":0,\"mp_initial_value_segment\":0,\"mp_id\":0,\"conversion_last_form_date\":0,\"conversion_last_form_id\":0,\"conversion_last_promo_id\":-1,\"last_message_date\":1446132368928,\"cg_version\":0,\"cg_version_date\":0,\"num_anon_messages_global\":0,\"num_anon_messages_global_date\":0,\"reg_creator_id\":576,\"reg_form_id\":101,\"reg_method_id\":1,\"reg_creator_type_id\":1},\"personal_data\":{\"version\":0,\"personal_data\":\"{}\",\"mdc_data\":{\"version\":0},\"custom_data\":\"{}\"},\"category_data\":{},\"campaignImpressions\":{},\"journeyStartDate\":0}","{\"company_id\":2979,\"data\":{\"drm_user_id\":572901936637129135,\"direct_status_id\":0,\"direct_optin_date\":0,\"direct_first_optin_date\":0,\"direct_last_optin_date\":0,\"direct_optout_date\":0,\"direct_last_form_date\":0,\"direct_last_form_id\":0,\"direct_last_promo_id\":0,\"anon_status_id\":600,\"anon_optin_date\":1446132360498,\"anon_first_optin_date\":1446132360498,\"anon_last_optin_date\":1446132360498,\"anon_optout_date\":0,\"anon_last_form_date\":1446132360498,\"anon_last_form_id\":101,\"anon_last_promo_id\":1002003,\"last_registration_date\":1446132360498,\"mp_status_id\":600,\"mp_control_state\":-1,\"mp_match_date\":0,\"mp_vs_version\":0,\"mp_initial_value_segment\":0,\"mp_id\":0,\"conversion_last_form_date\":0,\"conversion_last_form_id\":0,\"conversion_last_promo_id\":-1,\"last_message_date\":1446132368928,\"cg_version\":0,\"cg_version_date\":0,\"num_anon_messages_global\":0,\"num_anon_messages_global_date\":0,\"reg_creator_id\":576,\"reg_form_id\":101,\"reg_method_id\":1,\"reg_creator_type_id\":1},\"personal_data\":{\"version\":0,\"personal_data\":\"{}\",\"mdc_data\":{\"version\":0},\"custom_data\":\"{}\"},\"category_data\":{},\"campaignImpressions\":{},\"journeyStartDate\":0}"]
JSONParser parser = new JSONParser();
Object obj = parser.parse(test);
JSONArray array = (JSONArray)obj;
System.out.println(array.get("company_id"));
I think there is a object array. I think you can get you answer using following way.
for(int i=0;i<array.length();i++){
String company_id=array.getJSONObject(i).getString("company_id");
}

How to read JSON in Java?

I have a JSON String and I got the data element's data to JSONObject. After I read this that resultant string is as follows. I'm using org.json library.
String dataStr = "[{\"name\":\"jhonny\",\"counts\":[\"50\",\"44\",\"46\"],\"url\":\"google\"},
{\"name\":\"john\",\"counts\":[\"344\",\"4\",\"18\"],\"url\":\"yahoo\"}]";
I tried to read the each element like following,
String dataStr = report.get("data").toString();
JSONObject data = new JSONObject(dataStr.substring(1));
System.out.println(data);
But my output is,
{"name":"jhonny","counts":["50","44","46"],"url":"google"}
The output contains only one element. How can I fix this?
JSONArray jsonarray = new JSONArray(datastr);
for(int i=0; i<jsonarray.length(); i++){
JSONObject data= jsonarray.getJSONObject(i);
System.out.println(data);
}
Using the org.json library:
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("interestKey"));
}
The problem is you are trying to read JSONArray as JSONObject.
To parse JSONArray you need to do something like: (Not sure which library you are using)
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
// jsonobject holds the desired element.
}
If you analyze your json string, you will notice that your json string contains multiple json object without outer object like :-
{
"outer":{
{\"name\":\"jhonny\",\"counts\":[\"50\",\"44\",\"46\"],\"url\":\"google\"},
{\"name\":\"jhonny\",\"counts\":[\"50\",\"44\",\"46\"],\"url\":\"google\"}
}
}
The way you are parsing require this kind of json structure. Your json string is actually just a jsonarray. So do like this way :
JSONArray jsonarray = new JSONArray(datastr);
for(int i=0; i<jsonarray.length(); i++){
JSONObject data= jsonarray.getJSONObject(i);
}
For more you can visit this link that gives you good explanation to how to read json in java

Reading JSON on Android, No Output

This is my JSON data.
{"JSONDATA":[{"key":0,"value":"--Any--"},{"key":61,"value":"Accounting"},{"key":81,"value":"Aerospace & Defense"},{"key":72,"value":"Automotive"},{"key":83,"value":"Banking"},{"key":84,"value":"Biotech"},{"key":85,"value":"Construction"},{"key":86,"value":"Customer Service"},{"key":87,"value":"Education"},{"key":82,"value":"Energy"},{"key":70,"value":"Finance"},{"key":193,"value":"Government"},{"key":194,"value":"Healthcare"},{"key":71,"value":"Insurance"},{"key":73,"value":"Legal"},{"key":62,"value":"Management"},{"key":63,"value":"Manufacturing"},{"key":64,"value":"Marketing\/Advertising"},{"key":77,"value":"Media - Journalism"},{"key":74,"value":"Pharmaceutical"},{"key":75,"value":"Real Estate"},{"key":76,"value":"Research"},{"key":65,"value":"Restaurant"},{"key":66,"value":"Retail"},{"key":67,"value":"Sales"},{"key":78,"value":"Science"},{"key":68,"value":"Telecommunications"},{"key":79,"value":"Training"},{"key":69,"value":"Transportation"},{"key":80,"value":"Utilities"}]}
I want to decode it on my Android App, This is the code i have used., But i don't get anything on my output. No errors too.
JSONObject jObject= new JSONObject();
JSONArray menuObject = new JSONArray(jObject.getString("JSONDATA"));
String app;
for (int i = 0; i<menuObject.length(); i++) {
{
app=menuObject.getJSONObject(i).getString("value").toString();
a.append(app); // a is my TextView
}
First off, you're not initializing your jObject with anything.
//pass in string
JSONObject jObject= new JSONObject(jsonString);
JSONObjects need something to parse, otherwise (the way you have it now) they initialize with no data, which isn't very helpful.
Secondly, you're using getString when you really want an array:
JSONArray menuObject = jObject.getJSONArray("JSONDATA");
getString is designed to return a piece of string data from a JSON object. "JSONDATA" holds an array, so we need to choose the correct type to retrieve.
Thirdly, you have a redundant toString(), as getString already returns a String:
app=menuObject.getJSONObject(i).getString("value");
Its wrong:
JSONArray menuObject = new JSONArray(jObject.getString("JSONDATA"));
Try:
JSONObject jObject= new JSONObject(yourJSONString);
JSONArray menuObject = jObject.getJSONArray("JSONDATA");
Keep one thing in mind:
Create a JSON Object with JSON String you want to parse and then you can fetch String/JSON Object or JSON Array from the created JSON Object.
Store your json response in a String
String jsonResponse="YOUR JSON RESPONSE STRING";
//Pass the string as below
JSONObject jObject= new JSONObject(jsonResponse);
JSONArray menuObject = jObject.getJSONArray("JSONDATA"));
String app;
for (int i = 0; i<menuObject.length(); i++) {
{
app=menuObject.getJSONObject(i).getString("value").toString();
a.append(app); // a is my TextView
}
Use the appropiate getters and setters in JSONObject and JSONArray, and your "JSONDATA" entry is not a string. Do something like this:
JSONObject jObject = new JSONObject(yourJsonString);
JSONArray menuArray = jObject.getJSONArray("JSONDATA");
for (int i = 0; i < menuArray.length(); i++) {
String app = menuObject.getJSONObject(i).getString("value");
a.append(app); // a is my TextView
}
Use following code for parse your json string.
JSONObject obj = new JSONObject(youtString);
JSONArray array = obj.getJSONArray("JSONDATA");
for (int i = 0; i < array.length(); i++) {
JSONObject c = array.getJSONObject(i);
String key = c.getString("key");
String value = c.getString("value");
a.append(value);
}
Use this:-
String result="[{"key":0,"value":"--Any--"},{"key":61,"value":"Accounting"},{"key":81,"value":"Aerospace & Defense"},{"key":72,"value":"Automotive"},{"key":83,"value":"Banking"},{"key":84,"value":"Biotech"},{"key":85,"value":"Construction"},{"key":86,"value":"Customer Service"},{"key":87,"value":"Education"},{"key":82,"value":"Energy"},{"key":70,"value":"Finance"},{"key":193,"value":"Government"},{"key":194,"value":"Healthcare"},{"key":71,"value":"Insurance"},{"key":73,"value":"Legal"},{"key":62,"value":"Management"},{"key":63,"value":"Manufacturing"},{"key":64,"value":"Marketing\/Advertising"},{"key":77,"value":"Media - Journalism"},{"key":74,"value":"Pharmaceutical"},{"key":75,"value":"Real Estate"},{"key":76,"value":"Research"},{"key":65,"value":"Restaurant"},{"key":66,"value":"Retail"},{"key":67,"value":"Sales"},{"key":78,"value":"Science"},{"key":68,"value":"Telecommunications"},{"key":79,"value":"Training"},{"key":69,"value":"Transportation"},{"key":80,"value":"Utilities"}]";
JSONArray menuObject = new JSONArray(result);
String app;
for (int i = 0; i<menuObject.length(); i++) {
{
app=menuObject.getJSONObject(i).getString("value").toString();
a.append(app); // a is my TextView
}

How to put a List<class> into a JSONObject and then read that object?

I have a List<class> that I would like to convert into a json object and then traverse the data out of the json object.
If this were just a List<String> I could just do something like:
JSONObject obj = new JSONObject();
List<String> sList = new ArrayList<String>();
sList.add("val1");
sList.add("val2");
obj.put("list", sList);
Then I could traverse the list like:
JSONArray jArray = obj.getJSONArray("list");
for (int ii = 0; ii < jArray.size(); ii++)
System.out.println(jArray.getString(ii));
The problem with using the class is that I need to have access to data within each class element of my List<class> and I don't know how to encode that / traverse it into JSON. Any help would be greatly appreciated.
Call getJSONObject() instead of getString(). That will give you a handle on the JSON object in the array and then you can get the property off of the object from there.
For example, to get the property "value" from a List<SomeClass> where SomeClass has a String getValue() and setValue(String value):
JSONObject obj = new JSONObject();
List<SomeClass> sList = new ArrayList<SomeClass>();
SomeClass obj1 = new SomeClass();
obj1.setValue("val1");
sList.add(obj1);
SomeClass obj2 = new SomeClass();
obj2.setValue("val2");
sList.add(obj2);
obj.put("list", sList);
JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
System.out.println(jArray.getJSONObject(ii).getString("value"));
Let us assume that the class is Data with two objects name and dob which are both strings.
Initially, check if the list is empty. Then, add the objects from the list to a JSONArray
JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<Data>();
//if List not empty
if (!sList.isEmpty()) {
//Loop index size()
for(int index = 0; index < sList.size(); index++) {
JSONObject eachData = new JSONObject();
try {
eachData.put("name", sList.get(index).getName());
eachData.put("dob", sList.get(index).getDob());
} catch (JSONException e) {
e.printStackTrace();
}
allDataArray.put(eachData);
}
} else {
//Do something when sList is empty
}
Finally, add the JSONArray to a JSONObject.
JSONObject root = new JSONObject();
try {
root.put("data", allDataArray);
} catch (JSONException e) {
e.printStackTrace();
}
You can further get this data as a String too.
String jsonString = root.toString();
This is how I do it using Google Gson. I am not sure, if there are a simpler way to do this (with or without an external library).
Type collectionType = new TypeToken<List<Class>>() {
}.getType();
String gsonString = new Gson().toJson(objList, collectionType);
You could use a JSON serializer/deserializer like flexjson to do the conversion for you.
Just to update this thread, here is how to add a list (as a json array) into JSONObject.
Plz substitute YourClass with your class name;
List<YourClass> list = new ArrayList<>();
JSONObject jsonObject = new JSONObject();
org.codehaus.jackson.map.ObjectMapper objectMapper = new
org.codehaus.jackson.map.ObjectMapper();
org.codehaus.jackson.JsonNode listNode = objectMapper.valueToTree(list);
org.json.JSONArray request = new org.json.JSONArray(listNode.toString());
jsonObject.put("list", request);

Categories