How to get values from json String - java

I have a json string string from which I want to get the values. It is in key pair form so I want the values for each key.
I tried to get the values but I am not getting it.
Json String is like :
{
"document": {
"xmlns:xsi": "http:\/\/www.w3.org\/2001\/XMLSchema-instance",
"xsi:schemaLocation": "http:\/\/ocrsdk.com\/schema\/recognizeard-1.0.xsd http:\/\/ocrsdk.com\/schema\/recognized-1.0.xsd",
"xmlns": "http:\/\/ocrsdk.com\/schema\/recognize-1.0.xsd",
"businessCard": {
"imageRotation": "noRotation",
"field":
[{
"type": "Name",
"value": "Rafcev B. Agnrwal"
}, {
"type": "Company",
"value": "VJ>"
}, {
"type": "Text",
"value": "Dr. Rafcev B. Agnrwal\nMOB 0324%\nun\n) AOM*. founts. sso\nVJ>\nT"
}]
}
}
}
I want to get values of "Name", "Address", "Company" etc.
I tried to get like this:
JSONArray array;
if(mIntent.getStringExtra("jsonString") != null) {
Log.d("json", mIntent.getStringExtra("jsonString"));
try {
JSONObject object = new JSONObject(mIntent.getStringExtra("jsonString"));
array = object.getJSONArray("field");
for (int i = 0; i < array.length(); i++) {
JSONObject subObject1 = array.getJSONObject(i);
edt_FirstName.setText(object.getString("Name"));
}
} catch (JSONException e) {
}
Can anyone help me out please? Thank you..
EDIT:
I tried to check values like this:
for (int i = 0; i < array.length(); i++) {
JSONObject subObject1 = array.getJSONObject(0);
String type = subObject1.getString("type");
String value = subObject1.getString("value");
if (type.equals("Name")) {
edt_FirstName.setText(value);
}
if(type.equals("Address"))
{
edt_address.setText(value);
}
if(type.equals("Company"))
{
edt_company.setText(value);
}
if(type.equals("Mobile"))
{
edt_Mobile.setText(value);
}
}
I want to get all the values from field array and set to the text view, but I am getting only the Name value and not the others.
Also I could get one field as twice like Mobile I can get twice, so I want to combine both the Mobile values and show it.

So your json object is as follow:
{
"document": {
"xmlns:xsi": "http:\/\/www.w3.org\/2001\/XMLSchema-instance",
"xsi:schemaLocation": "http:\/\/ocrsdk.com\/schema\/recognizeard-1.0.xsd http:\/\/ocrsdk.com\/schema\/recognized-1.0.xsd",
"xmlns": "http:\/\/ocrsdk.com\/schema\/recognize-1.0.xsd",
"businessCard": {
"imageRotation": "noRotation",
"field":
[{
"type": "Name",
"value": "Rafcev B. Agnrwal"
}, {
"type": "Company",
"value": "VJ>"
}, {
"type": "Text",
"value": "Dr. Rafcev B. Agnrwal\nMOB 0324%\nun\n) AOM*. founts. sso\nVJ>\nT"
}]
}
}
}
You first need to get "document" as JSONObject and then get "businessCard" as JSONObject and then you can get "field" as JSONArray:
if(mIntent.getStringExtra("jsonString") != null) {
Log.d("json", mIntent.getStringExtra("jsonString"));
try {
JSONObject object = new JSONObject(mIntent.getStringExtra("jsonString"));
JSONArray array = object.getJSONObject("document").getJSONObject("businessCard").getJSONArray("field");
for (int i = 0; i < array.length(); i++) {
JSONObject subObject = array.getJSONObject(i);
String type = subObject.getString("type");
String value = subObject.getString("value");
if (type.equals("Name")) {
String prevValue = edt_FirstName.getText();
edt_FirstName.setText((TextUtils.isEmpty(prevValue) ? "" : prevValue + ",") + value);
}
}
} catch (JSONException e) { }
}

Try this code, Hope it will help you.
try
{
JSONObject jsonObject = new JSONObject();
JSONObject documentObject = jsonObject.getJSONObject("document");
JSONObject businessCardObject = documentObject.getJSONObject("businessCard");
String imgRotation = businessCardObject.getString("imageRotation");
JSONArray array = businessCardObject.getJSONArray("field");
for (int i = 0; i < array.length() ; i++)
{
JSONObject arrObj = array.getJSONObject(i);
String type = arrObj.getString("type");
String value = arrObj.getString("value");
Log.e(TAG, "type=="+type);
Log.e(TAG, "value=="+value);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}

here is code
private void convertJsonToDto(String jsonNewString) {
JSONObject jsonObj = new JSONObject(jsonNewString);
String RecordLocator = (String) jsonObj.get("obj");
String FirstName = (String) jsonObj.getJSONObject("Customer").get("FirstName");
JSONArray array = new JSONObject(jsonNewString).getJSONArray("Array");
JSONObject jsonObject = array.getJSONObject(0);
String str = jsonObject.getString("object");
}

Related

How to update few fields in JSON file and again read the JSON with updated values in selenium using Java

How to update few fields in JSON file and again read the JSON with updated values in selenium using Java.
Below is my JSON :
I want to update
{
"DemoFileJson": [
{
"name": "demoPan",
"Type": "patientcare",
"indication": "fever",
"disease": {
"code": "282292002",
"label": "Uncertain diagnosis"
},
"identified": false,
"specimens": [
{
"name": "primarySpecimen",
"type": {
"code": "442524009",
"label": "a.m. specimen"
},
"studyIdentifier": "Stud1",
"studySubjectIdentifier": "Part1",
"accessionNumber": "TSO500-MJ678",
"dateAccessioned": "2019-03-29T20:00:00Z",
"datecollected": "2019-03-29T20:00:00Z",
"dateReceived": "2019-03-29T20:00:00Z"
}
]
}
]
}
search & update value json file, with java class
example json file
[{"trx_id":"123"},{"trx_id":"123","datetime_expired":"20221102"}]
public class cariJSON {
public static void main(String[] args)throws Exception {
JSONArray dd = updateJson("datetime_expired", "20331001");
try (FileWriter file = new FileWriter("C://file.json")) { //store data
file.append(dd.toString());
file.flush();
}
System.out.println(dd);
}
public static JSONArray updateJson(String keyString, String newValue) throws Exception {
String jsons = readFileAsString("C://file.json");
JSONArray jsonArray = new JSONArray(jsons);
for (int j = 0; j < jsonArray.length(); j++)
{
JSONObject obj = new JSONObject(jsonArray.get(j).toString());
// get the keys of json object
if (obj.get("trx_id").equals("123"))
{
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
// if the key is a string, then update the value
if ((obj.optJSONArray(key) == null) && (obj.optJSONObject(key) == null)) {
if ((key.equals(keyString))) {
obj.put(key, newValue);
jsonArray.remove(j);
return jsonArray.put(obj);
}
}
// if it's jsonobject
if (obj.optJSONObject(key) != null) {
updateJson(keyString, newValue);
}
// if it's jsonarray
if (obj.optJSONArray(key) != null) {
JSONArray jArray = obj.getJSONArray(key);
for (int i = 0; i < jArray.length(); i++) {
updateJson(keyString, newValue);
}
}
}
}
System.out.println("Output array : " + jsonArray);
return jsonArray;
}
return null;
}
}

Transform a JsonArray into an ArrayList

I have this json that i got using the YoutubeAPI :
{
"items": [
{
"id": {
"videoId": "ob1ogBV9_iE"
},
"snippet": {
"title": "13 estrellas ",
"description": "Pueden encontrar estas "
}
},
{
"id": {
"videoId": "o9vsXyrola4"
},
"snippet": {
"title": "Rayos CoĢsmicos ",
"description": "Este es un programa piloto "
}
}
]
}
i want to save the fiel "id" on an ArrayList but i have some problems this is the code im using:
JSONArray jsonArray = myResponse.getJSONArray("items");
In this line im creating an JSONarray with the JSONobject i created first
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject json = jsonArray.getJSONObject(i);
list.add(json.getString("videoID"));
} catch (JSONException e) {
e.printStackTrace();
}
}
My question is how can i access to this field? and how can i save it
You've got two main issues. The first is that "videoID" and "videoId" are not the same string. So you're checking for a key that doesn't exist.
Your second problem is that the "videoId" key doesn't exist in the top level object, it's inside the "id" object, so you need to drill down an extra layer to get it:
JSONArray jsonArray = myResponse.getJSONArray("items");
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject json = jsonArray.getJSONObject(i);
JSONObject id = json.getJSONObject("id");
list.add(id.getString("videoId"));
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println(list); // [ob1ogBV9_iE, o9vsXyrola4]
Try with correct case for videoId, like
list.add(json.getString("videoId"));

my json parser for jsonarry just get the first element

i have parser function that parse json array and return arrays that i use it in a list adapter and then the adapter is used by a recyclerview .it's giving me the actual length but only the first element of the arrays is filled while the others return NULL
that is my code
public void parsee_item() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
final JSONArray userss = jsonObject.getJSONArray(JSON_ARRAY);
item_id = new String[userss.length()];
item_owner = new String[userss.length()];
item_images = new String[userss.length()];
item_names = new String[userss.length()];
item_price = new String[userss.length()];
item_place = new String[userss.length()];
JSONObject jo = null;
for (int i = 0; i < userss.length();i++) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
the json is
{
"result": [{
"item_id": "10",
"owner": "user",
"item_type_id": "1",
"url1": "http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "jc",
"price": "76"
}, {
"item_id": "12",
"owner": "user",
"item_type_id": "1",
"url1": " http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "nzbsbsb",
"price": "0"
}, {
"item_id": "13",
"owner": "user",
"item_type_id": "1",
"url1": " http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "uygf",
"price": "0"
}]
}
and this screenshot of the list
enter image description here
it's not suggested parsing json yourself ,use a Json Parse Util such as Gson or fastJson instead .
I used your code, debug, and found values are updated their is no error with JSON paring, So check your recycler view adapter code or share it
Replace this line
jo = userss.getJSONObject(4);
with this
jo = userss.getJSONObject(i);
JSONObject jo = null;
for (int i = 0; i < userss.length();i++) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
item_place[i] = jo.getString("place");
}
the problem with ur code is you use hardcode value 4
jo = userss.getJSONObject(4);
insted of this use
jo = userss.getJSONObject(i);
at each and every time you are parsing the index 4 jsonObject information
public void parsee_item() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
final JSONArray userss = jsonObject.getJSONArray(JSON_ARRAY);
item_id = new String[userss.length()];
item_owner = new String[userss.length()];
item_images = new String[userss.length()];
item_names = new String[userss.length()];
item_price = new String[userss.length()];
item_place = new String[userss.length()];
JSONObject jo = null;
for (int i = 0; i < userss.length();) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
item_place[i] = jo.getString("place");
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
if you use this type of parsing it may lead to null pointer exception
You can parse above JSON as follows
private void jsonParse(String response) throws JSONException {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
if (object != null) {
String itemId = object.getString("item_id");
String owner = object.getString("owner");
String item_type_id = object.getString("item_type_id");
String url1 = object.getString("url1");
String name = object.getString("name");
String price = object.getString("price");
}
}
}
}
i was receiving a parameter that wasn't being sent by the jsonarray
item_place[i] = jo.getString("place")

Can't get value from JSON Data - YouTube API -

I'v try to get an value from a json data (YouTube V3 API).
String jsonText = readFromUrl(channerUrl);// channerUrl = Youtube V3 API Link
JSONObject json = new JSONObject(jsonText);
System.out.println(json.getString("videoId"));
But i have this in my log :
I/System.out: org.json.JSONException: No value for videoId
The data from YouTube is :
{
"kind": "youtube#playlistItemListResponse",
"etag": "\"xxxx"",
"nextPageToken": "xxx",
"pageInfo": {
"totalResults": 321,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#playlistItem",
"etag": "\"xxxx"",
"id": "xxxx",
"contentDetails": {
"videoId": "The Value Want"
}
}
]
}
Why i have No value for videoId ?
Thank you
EDIT (didn't work too) : (jsonText) is the link of the JSON Data
JSONObject json = new JSONObject(jsonText);
List<String> list = new ArrayList<String>();
JSONArray array = json.getJSONArray("items");
for(int i = 0 ; i < array.length() ; i++){
list.add(array.getJSONObject(i).getString("contentDetails"));
System.out.println(json.getString("contentDetails"));
}
Because videoId is under items object.
Get item first then get its first child then fet the videoId
Edit: use
array.getJSONObject(i).getJSONObject("contentDetails").getString("videoId")
And remove the println line
Then outside the loop just print the list that contains the videoIds
use this code :
JSONObject json = new JSONObject(jsonText);
List<String> list = new ArrayList<String>();
JSONArray array = null;
try {
array = json.getJSONArray("items");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0 ; i < array.length() ; i++){
// list.add(array.getJSONObject(i).getString("contentDetails"));
try {
System.out.println(array.getJSONObject(i).getJSONObject("contentDetails").getString("videoId"));
} catch (JSONException e) {
e.printStackTrace();
}
}
try
{
JSONObject mJsonObject = new JSONObject(strValue);
JSONArray items = mJsonObject.getJSONArray("items");
String nextToken = mJsonObject.getString("nextPageToken").toString();
for(int i = 0;i<items.length();i++)
{
JSONObject snipetts = items.getJSONObject(i);
JSONObject snipet = snipetts.getJSONObject("snippet");
JSONObject thumbnails = snipet.getJSONObject("thumbnails");
JSONObject highImage = thumbnails .getJSONObject("high");
String title = snipet.get("title").toString();
String urlImage = highImage.get("url").toString();
String videoID = snipetts.getString("id");
String description = snipet.getString("description");
String publishDate = snipet.getString("publishedAt");
}
}
catch (Exception e)
{
e.printStackTrace();
}

Add JSON entry into an array to use in ListView

I have the following code which gets the number how many times a select entry appears:
int k = 0;
int j = 0;
try {
jsonArray = new JSONArray(result);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the josn object
if(jsonObj.getString("type").equals("image")) { // compare for the key-value
k++;
}
if(jsonObj.getString("type").equals("text")) { // compare for the key-value
j++;
}
}
Toast.makeText(getApplicationContext(), String.valueOf(k), 2000).show();
Toast.makeText(getApplicationContext(), String.valueOf(j), 2000).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
My JSON file is:
[
{
"id": "12",
"type": "text",
"data": "This is a test"
},
{
"id": "5465465",
"type": "image",
"data": "http://pagesbyz.com/theImages/gallery/portfolio_app07.png"
},
{
"id": "982",
"type": "text",
"data": "THIS IS A TEST TEXT"
},
{
"id": "5500",
"type": "text",
"data": "http://pagesbyz.com/theImages/gallery/portfolio_app03.png"
}
]
So... k = 1 and j = 3
How can I get the entire array for the matched entry?
For example once the type equals image I want an array set up to hold the information.
How do I translate the following in Java?
for (as many times an "image" entry appears) {
if ( type == "image") {
imgarr[index found][id] = "5465465";
imgarr[index found][type] = "image";
imgarr[index found][data] = "http://pagesbyz.com/theImages/gallery/portfolio_app07.png";
}
}
for (as many times an "text" entry appears) {
if ( type == "text") {
txtarr[index found][id] = "12";
txtarr[index found][type] = "text";
txtarr[index found][data] = "This is a test";
txtarr[index found][id] = "082";
txtarr[index found][id] = "text";
txtarr[index found][id] = "THIS IS A TEST TEXT";
and so forth...
}
}
And the same for type equals "text"?
create 2 new jsonArray variables, one for image and one for type, whenever the type is image add the object to jsonimage and same for jsontext
try {
JSONArray jsonimage = new JSONArray();
JSONArray jsontext = new JSONArray();
jsonArray = new JSONArray(result);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = (JSONObject)jsonArray.get(i); // get the josn object
if(jsonObj.getString("type").equals("image")) { // compare for the key-value
jsonimage.put(jsonObj);
k++;
}
if(jsonObj.getString("type").equals("text")) { // compare for the key-value
jsontext.put(jsonObj);
j++;
}
}
Toast.makeText(getApplicationContext(), String.valueOf(k), 2000).show();
Toast.makeText(getApplicationContext(), String.valueOf(j), 2000).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
hope this is what you are looking for or give you a hint.
EDIT:
to add the jsonArray to the listview, you can either create a hashMap or simply create String of strings for each entry in the JSONArray.
String sId = new String[jsonimage.length()];
String sType = new String[jsonimage.length()];
String sData = new String[jsonimage.length()];
for (int i = 0 ; i < jsonimage.length(); i++)
{
JSONObject c = jsonimage.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
String data = c.getString("data");
sId[i] = id;
sType[i] = type;
sData[i] = data;
}
then after you having your data from the JSONArray...
have a custom view that holds 3 textview and add this
listView.setAdapter(new CustomAdapter(yourClass.this));
and simply add the generated String[position] in getView of the CustomAdapter

Categories