getString not working for JSON key - java

I'm learning how to work with JSON's in java and I'm having a problem using getString for one of my keys. My code is here:
public static void getJSON(String matchID){
String s = "";
String test = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"}]}";
try {
JSONObject hi = new JSONObject(test);
JSONArray stuff = hi.getJSONArray("employees");
String[] items = new String[stuff.length()];
items[0] = stuff.getString("firstName");
} catch (JSONException e) {
e.printStackTrace();
}
}
The "getString" is underlined in red, and the "The method getString(int) in the type JSONArray is not applicable for the arguments (String)" I was following an answer to another question word for word almost, and this happens, any advice? Thanks!
EDIT:
I need to get the specifics by name ie. "firstName" because I will be working with thousands of JSONs that each have hundreds of lines.

You need to get the JSOnObject first from the JSONArray(stuff) before you can call getString().
if you want to get the first element in the jsonarray and get its string this is how you would do it
JsonObject obj = stuff.getJsonObject(0);
String name = obj.getString("firstname");

So I figured out my problem, I didn't realize I had an JSONObject first, my apologies. Fixed like this:
JSONObject hi = new JSONObject(test);
JSONArray stuff = hi.getJSONArray("employees");
JSONObject name = stuff.getJSONObject(0);
String[] items = new String[hi.length()];
items[0]=name.getString("firstName");
System.out.println(items[0]);

you can try the simplest way to Parse in JSON
JSONParser parser=new JSONParser();
String s = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"}]}";
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println(array.get(1));
}catch(ParseException pe){
}

Related

Convert Json String to List in Android

strResponse = {"GetCitiesResult":["1-Vizag","2-Hyderbad","3-Pune","4-Chennai","9-123","11-Rohatash","12-gopi","13-Rohatash","14-Rohatash","10-123"]}
JSONObject json = new JSONObject(strResponse);
// get LL json object
String json_LL = json.getJSONObject("GetCitiesResult").toString();
Now i want to convert the json string to List in andriod
Please make sure your response String is correct format, if it is, then try this:
try {
ArrayList<String> list = new ArrayList<String>();
JSONObject json = new JSONObject(strResponse);
JSONArray array = json.getJSONArray("GetCitiesResult");
for (int i = 0; i < array.length(); i++) {
list.add(array.getString(i));
}
} catch (Exception e) {
e.printStackTrace();
}
Simply using Gson library you can convert json response to pojo class.
Copy the json string to create pojo structure using this link: http://www.jsonschema2pojo.org/
Gson gson = new Gson();
GetCitiesResult citiesResult = gson.fromJson(responseString, GetCitiesResult.class);
It will give the GetCitiesResult object inside that object you get a list of your response like
public List<String> getGetCitiesResult() {
return getCitiesResult;
}
Call only citiesResult.getGetCitiesResult(); it will give a list of cities.
You can also use this library com.squareup.retrofit2:converter-gson:2.1.0
This piece of code did the trick
List<String> list3 = json.getJSONArray("GetCitiesResult").toList()
.stream()
.map(o -> (String) o)
.collect(Collectors.toList());
list3.forEach(System.out::println);
And printed:
1-Vizag
2-Hyderbad
3-Pune
4-Chennai
9-123
11-Rohatash
12-gopi
13-Rohatash
14-Rohatash
10-123
below is code:
private void parse(String response) {
try {
List<String> stringList = new ArrayList<>();
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("GetCitiesResult");
for (int i=0; i <jsonArray.length(); i++){
stringList.add(jsonArray.getString(i));
}
Log.d ("asd", "--------"+ stringList);
} catch (Exception e) {
e.printStackTrace();
}
}
Hope it will help.
Output is when print list :
--------[1-Vizag, 2-Hyderbad, 3-Pune, 4-Chennai, 9-123, 11-Rohatash, 12-gopi, 13-Rohatash, 14-Rohatash, 10-123]
Ok you must know first something about JSON
Json object is be {// some attribute}
Json Array is be [// some attribute]
Now You have
{"GetCitiesResult":["1-Vizag","2-Hyderbad",
"3-Pune","4-Chennai","9-123","11-Rohatash",
"12-gopi","13-Rohatash","14-Rohatash","10-123"]}
That`s Means you have JSON array is GetCitiesResult
which have array of String
Now Try this
JSONObject obj = new JSONObject(data);
JSONArray loadeddata = new JSONArray(obj.getString("GetCitiesResult"));
for (int i = 0; i <DoctorData.length(); i++) {// what to do here}
where data is your String

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");
}

Convert returned JSON String to a JSONArray

I have a web service that performs a database query, converts the result set to a JSON String and returns the strung to the client. This is the code for the converter (I got it from http://biercoff.com/nice-and-simple-converter-of-java-resultset-into-jsonarray-or-xml/):
public static String convertToJSON(ResultSet resultSet)
throws Exception {
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < total_rows; i++) {
obj.put(resultSet.getMetaData().getColumnLabel(i + 1)
.toLowerCase(), resultSet.getObject(i + 1));
}
jsonArray.add(obj);
}
return jsonArray.toJSONString();
}
In the client application when I print the returned string it is in the following format:
[{"Column1":0.333333,"Column2":"FirmA"},{"Column1":0.666667,"Column2":"FirmB"}]
so far all is good. The problem I am having is converting the returned string into a JSON array. I tried this:
JSONArray arr = new JSONArray(JSON_STRING);
but got the following error message: constructor JSONArray in class JSONArray cannot be applied to given types. I tried to first convert in into a JSON object like so:
JSONObject obj = new JSONObject(JSON_STRING);
but got the following error: incompatible types: String cannot be converted to Map. What am I doing wrong? Thanks.
Apparently the problem was with the json library that I was using. Once I used the
import org.json.JSONArray;
it all worked out well. I was able to convert the returned string to an array using
JSONArray arr = new JSONArray(JSON_STRING);
and to iterate through the values I used the code provided in this answer: Accessing members of items in a JSONArray with Java which I reproduce here for simplicity:
for (int i = 0; i < arr.length(); ++i) {
JSONObject rec = arr.getJSONObject(i);
int id = rec.getInt("id");
String loc = rec.getString("loc");
// ...
}
well you need to do it by this way for example
String jsonText = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
try {
JSONArray array = new JSONArray(jsonText);
System.out.println(array);
System.out.println(array.length());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Check the correct library used. The mess is that org.json.simple is often suggested by IDE as default for JSONObject and JSONArray.
You can find a link to latest jar for org.json library above.

how to read JSON from HTTP GET request?

I have created a java server which gets HTTP GET request url as
/Star/getDetails?sentMsg=data.requestorName:ABC,data.companyName:EFG,portfolios:
[{name:,placeholder:Portfolio 1,positions:[{ticker:T1234,weight:29.85},
{ticker:T2345,weight:70.15}],active:false}],analyticsDate:20140630}
I have to parse sentMsg parameter such as I am able to read each variable individually. For eg, i should be able to read data.requestorName, companyName. I am not able to find a way to do it.
request.getParameter("sentMsg") always return String.
Tried parsing it through json-simple
JSONParser jp = new JSONParser();
try {
Object obj = jp.parse(sentMsg);
JSONArray ja = (JSONArray)obj;
} catch (ParseException e) {
e.printStackTrace();
}
But this gives parse exception. I have limitation to use json-simple jar only. Any suggestion on how to do it?
Get the paramter sentMsg from HttpRequest object store it into a string. Split from comma i.e. "," and the last second token would be the json string. You can now parse it using Json simple lib and extract values from it.
Provided you have valid JSON like:
private static String jsonString = "[{name : \"stackOverFlow\"}]";
Convert it to JSONArray like:
JSONArray jsonArray = new JSONArray(jsonString );
Then you can get value out of JSONArray by looping through it:
for (int i = 0; i < jsonArray.length(); i++) { //Iterating over mediaArray
JSONObject media = jsonArray.getJSONObject(i);
String nameFromJSON = media.getString("name");
System.out.println("Name = " + nameFromJSON);
}
Output will be:
//Name = stackOverFlow

Android Converting String to JSON [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I need advice into how to work out a method in Android which has to pick a string loaded with JSON data and then convert it back to JSON.
For the time being, I have programmed the following but I'm not sure if I'm on the right track or not.
private void convert_JSON()
{
String json;
//funcions per a cridar el string amb JSON i convertir-lo de nou a JSON
JSONArray jsas = new JSONArray();
for (int i =0; i < jsas.length(); i++)
{
JSONObject message = jsas.getJSONObject(i);
String content = message.getString("content");
}
}
The JSON is loaded into a String in this other method:
private void read_JSON(String json)
{
JSONObject jObject = new JSONObject(json);
JSONArray jso3 = new JSONArray (jObject.getString("Nombres_Hijos"));
String name = jso3.getString("Nombre");
System.out.println(name);
String surname = jso3.getString("Apellidos");
System.out.println(surname);
int date = jso3.getInt("Año_nacimiento");
System.out.println(date);
JSONArray jsa2 = jso3.getJSONArray ("Nombres_Hijos");
String names = jsa2.toString();
for (int i=0; i < jsa2.length(); i++)
{
System.out.println(jsa2.getString(i));
}
jso3.toString(json);
}
And, lastly, the JSON is created within the MainActivity.java, not as a split file yet that does work correctly:
private void create_JSON(String json)
{
JSONObject jso = new JSONObject();
try {
jso.put("Nombre","Miguel");
jso.put("Apellidos", "Garcia");
jso.put("Año_nacimiento", 1990);
JSONArray jsa = new JSONArray();
jsa.put("Blur");
jsa.put("Clur");
jso.put("Nombres_Hijos", jsa);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jso.toString();
In short: what I want to know is if my method convert_JSON is on the right track or I'm misunderstanding how it's supposed to work like.
Thank you very much for your help.
Yours sincerely,
Mauro.
You can convert a jsonstring back to json using the following JSONObject(String json) constructor:
JSONObject jsonObject = new JSONObject(jsonString);
Just, put it inside a try catch block and you should be good to go :)
You can create a JSONObject from a String using the constructor:
JSONObject json = new JSONObject(myString);
And to convert your JSONObject to a String, just use the toString() method:
String myString = json.toString();
Additionally, if you are trying to get a specific String value from the JSONObject, you can do this:
if (json.has("content"))
{
String content = json.getString("content");
//do something with content string
}
Finally, if you aren't very comfortable using JSONObject, I recommend using the tools provided by droidQuery to help you parse, such as:
Object[] array = $.toArray(myJSONArray);
and
Map<String, ?> map = $.map(myJSONObject);
If you want a pure copy/paste example have a look here
Alternatively I would suggest using one of the many well documented libraries. My personal favourite is GSON
Plenty of examples on the net on how to use this.

Categories