I am new in Java and I try to search and try many ways to get USER_NAME and PASSWORD in JSONObject
here my code:
JSONObject data = new JSONObject();
JSONObject input = inputHeader.generateInputHeader("ABCD001");
JSONObject jsonResponse = requestService.startRequestTransactionHttp(input);
if(jsonResponse.getString("RES_ID").toString().equals("000")) {
//here I want get USER_NAME and PASSWORD
}
Here is what jsonResponse respond
{ "RES_ID" : "000", "DATA" : { "PASSWORD" : "123456", "USER_NAME" : "abcd" }, "RES_MSG" : "OK!"}
please help me to solve it.
From docs, you should use:
JSONObject data = jsonResponse.getObject("DATA");
String username = data.getString("USER_NAME");
String password = data.getString("PASSWORD");
You can use following to access the nested objects -
JSONObject data= jsonResponse.getJSONObject("DATA");
data.getString("USER_NAME");
data.getString("PASSWORD");
Related
i am trying to phrase the below json response and the get the "message" and "WORKORDERID" data in java
{
"operation": {
"result": {
"message": " successfully.",
"status": "Success"
},
"Details": {
"SUBJECT": "qqq",
"WORKORDERID": "800841"
}
}
}
Below is my code
JSONObject inputs = new JSONObject(jsonResponse);
JSONObject jsonobject = (JSONObject) inputs.get("operation");
String s = jsonobject.getString("message");
system.out.println("s");
Your objects are nested 2 times, therefore you should do:
JSONObject inputs = new JSONObject(jsonResponse);
JSONObject operation= (JSONObject) inputs.get("operation");
JSONObject result= (JSONObject) operation.get("result");
JSONObject details= (JSONObject) operation.get("Details");
String message = result.getString("message");
String workerId = details.getString("WORKORDERID");
JSONObject is somethink like Map-Wrapper, so you can think, that your JSON data-structure is Map<Map<Map<String, Object>, Object>, Object>. So, firstly you need to access to datas by first key (operation), secondly (result) and after that, you can access to desired field (message).
Note, that value of Map is Object, so you will need to cast your type to JSONObject.
sometimes JSONObject class is not found in java. so you will need to add jar
try{
// build the json object as follows
JSONObject jo = new JSONObject(jsonString);
// get operation as json object
JSONObject operation= (JSONObject) jo.get("operation");
// get result as json object
JSONObject result= (JSONObject) jo.get("result");
JSONObject details= (JSONObject) jo.get("Details");
// get string from the json object
String message = jo.getString("message");
String workerId = jo.getString("WORKORDERID");
}catch(JSONException e){
System.out.println(e.getMessage());
}
"biodata": {
"Ruby": {
"Expertise": "web development",
"EXperience": "5 years"
},
"Dylon": {
"Expertise": "Java",
"EXperience": "2 years"
}
}
I have the above JSONObject . I am trying to fetch some keys here .
I am looking to fetch the name key i.e Ruby , Dylon etc .
I am then trying to fetch the "Experience " key value .
Desired output :
name= Ruby
Experience = 5 years
My code :
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("path to JSON file"));
JSONObject jsonobj = (JSONObject) obj;
String statistics = jsonobj.getString("biodata"); //The method getString(String) is undefined for the type JSONObject
for (Iterator key = jsonobj.keys(); itr.hasNext();) {//The method keys() is undefined for the type JSONObject //itr cannot be resolved
JSONObject name = jsonobj.get(key.next()); //Type mismatch: cannot convert from Object to JSONObject
String key = key.next();//The method next() is undefined for the type String
JSONObject name = jsonobj.get(key); //Type mismatch: cannot convert from Object to JSONObject
Log.d("data", "key="+key+ " and value="+jsonobj.toString()); //Log cannot be resolved
}
I have mentioned the errors in the comment of my code .
You json is not valid .
You should change to this .
{
"biodata": {
"Ruby": {
"Expertise": "web development",
"EXperience": "5 years"
},
"Dylon": {
"Expertise": "Java",
"EXperience": "2 years"
}
}
}
Try this .
private void jsonParse() {
try {
// use jsonobject to parse json with
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("path to JSON file"));
JSONObject jsonObject = (JSONObject) obj;
// get jsonobject by biodata tag
JSONObject biodata = jsonObject.getJSONObject("biodata");
// use Iterator to get name
Iterator<String> names = biodata.keys();
// use while loop
while (names.hasNext()) {
// get name
String name = names.next().toString();
Log.d("data", "name=" + name);
// get jsonobject by name tag
JSONObject nameJsonObject = biodata.getJSONObject(name);
// get string
String Expertise = nameJsonObject.getString("Expertise");
String EXperience = nameJsonObject.getString("EXperience");
Log.d("data", "Experience =" + EXperience);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
You have many issues in your code.
First: Assuming you want to implement code based on your current JSON String
Issues:
JSONObject API do not facilitate the methods of Map used in your implementation.
Your JSON String is not a array so for loop is not going to help, instead you should fetch the inner JSONObjects using the getJSONObject () method of the JSONObject API.
Casting the parsed object from your parser API will not automatically make it a JSONObject, the right way of doing this as below:
JsonObject jsonObject = parser.parse(new FileReader("path to JSON file")).getAsJsonObject();
Second: Assuming you intent to implement the JSON string representation as array, you should correct your JSON string as below.
"biodata": [{ "Ruby": { "Expertise": "web development", "EXperience": "5 years" }}, {"Dylon": { "Expertise": "Java", "EXperience": "2 years" } }]
With the above JSON string you can implement the fetching of data logic using JSONArray API
I am working on Yahoo Finance. Trying to parse json data from a url, such as Google finance data.
I am fetching data into a string "str" and then parsing the json data to reach the name field inside resources.
the json data is :
{
"list":{
"meta":{
"type":"resource-list",
"start":0,
"count":1
},
"resources":[
{
"resource":{
"classname":"Quote",
"fields":{
"name":"Alphabet Inc.",
"price":"710.489990",
"symbol":"GOOGL",
"ts":"1452891600",
"type":"equity",
"utctime":"2016-01-15T21:00:00+0000",
"volume":"3833751"
}
}
}
]
}
}
I am trying to use this code, but it is not working - need to reach the "name" field:
str4 = Client.execute(httpget, responseHandler);
//str holds the json data given above- checked.
JSONObject str1 = new JSONObject(str4);
JSONObject list = str1.getJSONObject("list");
JSONArray resources = list.getJSONArray("resorces");
JSONObject fields = resources.getJSONObject(1);
str2 = fields.getString("name");
I notices three issues with your code:
you have one item in your JSONArray, so you should retrieve item 0, not item 1.
you misspelled the word resources in your code.
Also, I think you didn't retrieve the fields correctly. This should do it:
JSONObject str1 = new JSONObject(str4);
JSONObject list = str1.getJSONObject("list");
JSONArray resources = list.getJSONArray("resources");
JSONObject fields = resources.getJSONObject(0).getJSONObject("resource").getJSONObject("fields");
str2 = fields.getString("name");
I have json string data like:
{"contactlist":["{"id":"1","mobile":"186010855","name":"Intex"}","{"id":"212","mobile":"980067","name":"pari"}"]}
I want to fetch all data means id,mobile and name for all..
So, I have Contact Class :
public class Contact {
private String id;
private String name;
private String mobile;
//getters and settrs & constructors
}
and for fetching I have tried:
String stringdata=
"{"contactlist":["{"id":"1","mobile":"186010855","name":"Intex"}","
{"id":"212","mobile":"980067","name":"pari"}"]}";
try{
Contact contact1 = new Contact();
contact1 = new Gson().fromJson(contactreceive, Contact.class);
Contact contact = new Contact(contact1.getId(),contact1.getName(),
contact1.getMobile());
System.out.println (contact);
}catch(Exception e){
}
But I can not fetch data like this..how can I fetch this json data?
Your JSON is invalid, as per #ShubhamChaurasia 's comment. The following JSON validates:
{
"contactlist": [{
"id": "1",
"mobile": "186010855",
"name": "Intex"
},
{
"id": "212",
"mobile": "980067",
"name": "pari"
}]
}
Escape this in Java as you have already been shown (with \") and this will stop your JSON validation errors. I recommend combining this with #Joopkins ' or #JanTheGun 's answer.
A good site I use for JSON validation is http://jsonlint.com/.
You need to escape the double quotes to get a valid json string. Then you can read the json array like this:
String stringdata = "{\"contactlist\":[{\"id\":\"1\",\"mobile\":\"186010855\",\"name\":\"Intex\"},{\"id\":\"212\",\"mobile\":\"980067\",\"name\":\"pari\"}]}";
JsonElement jsonElement = new JsonParser().parse(stringdata);
JsonObject jsonOject = jsonElement.getAsJsonObject();
JsonArray jsonArray = jsonOject.getAsJsonArray("contactlist");
for (JsonElement element : jsonArray) {
JsonObject obj = element.getAsJsonObject();
String id = obj.get("id").toString();
String name = obj.get("name").toString();
String mobile = obj.get("mobile").toString();
Contact contact = new Contact(id, name, mobile);
System.out.println("id: " + contact.getId());
System.out.println("name: " + contact.getName());
System.out.println("mobile: " + contact.getMobile());
System.out.println("");
}
You can convert the stringdata into a JSONArray containing a JSONObject for each contact.
JSONObject contactData = new JSONObject(stringdata);
JSONArray contactArray = contactData.getJSONArray("contactlist");
//Create an array of contacts to store the data
Contact[] contacts = new Contact[contactArray.length()];
//Step through the array of JSONObjects and convert them to your Java class
Gson gson = new Gson();
for(int i = 0; i < contactArray.length(); i++){
contacts[i] = gson.fromJson(
contactArray.getJSONObject(i).toString(), Contact.class);
}
Now you have an array of Contacts from your raw JSON data.
JSONObject contactData = new JSONObject(stringdata);
JSONArray contactArray = contactData.getJSONArray("contactlist");
for(int i=0;i<contactArray .length;i++){
JSONObject jsonObject=contactArray.getJSONObject(i));
String id=jsonObject.getString("id")
String key=jsonObject.getString("key")
}
I'm trying to parse json with an edittext, make it match for an id, and load the data it carries in textview. Im not really sure how to go about this, whether im using the right JSON, or if im using the right way to determine the most efficiet way to handle this. When i enter '5' in the edittext, i get the error mentioned below:
Error:
org.json.JSONException: No value for id
The JSON from url being parsed:
{
"id": "5",
"first_name": "Larry",
"last_name": "Gonzales",
"email": "lgonzales4#msu.edu",
"country": "Japan",
"ip_address": "242.198.195.241"
}
Java:
try {
JSONObject e = new JSONObject();
JSONObject jsonobjectidloader = e.getJSONObject(TAG_ID);
if (jsonobjectidloader.equals(xyz)){
uid.setText(id3);
id3 = jsonobjectidloader.getString(TAG_ID);
name1.setText(fname);
fname = jsonobjectidloader.getString(TAG_FIRST_NAME);
name2.setText(lname);
lname = jsonobjectidloader.getString(TAG_LAST_NAME);
email1.setText(email);
email = jsonobjectidloader.getString(TAG_EMAIL);
ipaddres.setText(ipa);
ipa = jsonobjectidloader.getString(TAG_IP);
cou.setText(country);
country = jsonobjectidloader.getString(TAG_COUNTRY);
I hope you guys can help me with this, im really stumped right now.
JSONObject e = new JSONObject(response.toString());
String id3 = e.getString(TAG_ID);
Response is your json from server
Use following code.
JSONObject jsonobjectidloader= new JSONObject(YOUR_JSON_STRING);
if (jsonobjectidloader.equals(xyz)){
id3 = jsonobjectidloader.getString(TAG_ID);
uid.setText(id3);
fname = jsonobjectidloader.getString(TAG_FIRST_NAME);
name1.setText(fname);
lname = jsonobjectidloader.getString(TAG_LAST_NAME);
name2.setText(lname);
email = jsonobjectidloader.getString(TAG_EMAIL);
email1.setText(email);
ipa = jsonobjectidloader.getString(TAG_IP);
ipaddres.setText(ipa);
country = jsonobjectidloader.getString(TAG_COUNTRY);
cou.setText(country);
just use it as
String json = '{"id":"5","first_name":"Larry","last_name":"Gonzales","email":"lgonzales4#msu.edu","country":"Japan","ip_address":"242.198.195.241"}';
e = new JSONObject(json);
.....
you need to actually provide the string to jsonboject constructor as argument.