This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed last year.
I have a method named getPayDetails() which return type is a string
pay.getPaymentDetails() of which return type is a string and it returns the below string
[
{
"mcTtid":201657083281,
"cardLast4Digits":"0887",
"paymentType":"CREDIT CARD",
"originalPaymentCategory":{
"code":"Q",
"name":"CREDIT CARD"
}
},
{
"veTtid":21656148003,
"cardLast4Digits":"4777",
"paymentType":"GIFT CARD",
"originalPaymentCategory":{
"code":"Q",
"name":"GIFT CARD"
}
},
{
"mcTtid":201625819,
"cardLast4Digits":"8388",
"paymentType":"GIFT CARD",
"originalPaymentCategory":{
"code":"w",
"name":"GIFT CARD"
}
}
]
I need to extract the value of the attribute paymentType from the above string so the value of attribute paymentType in the above string is CREDIT CARD in a separate string variable. how can I do this?
I would recommend to use org.json library that is very easy.
After that something like this
import org.json.*;
String jsonString = ... ; //assign your JSON String here
JSONArray arr = new JSONArray(jsonString);
for (int i = 0; i < arr.length(); i++)
{
String paymentType = arr.getJSONObject(i).getString("paymentType");
}
Related
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 2 years ago.
I got stuck in parsing this JSON, I has read a some references in GitHub or google and not same for this case, can anyone give me guided or references
{
"index":
{
"data":[
{
"id":1,
"name":"John",
"room":31
}
]
}
}
EDIT: we has found a more simple json format
The solve by me
{
"data":[
{
"id":1,
"name":"John",
"room":31
}
]
}
try {
JSONObject jsonArray = new JSONObject(response);
JSONArray list = jsonArray.getJSONArray("data");
for (int i = 0; i <list.length(); i++) {
String id= list.getJSONObject(i).getString("id");
String name = list.getJSONObject(i).getString("name");
String room= list.getJSONObject(i).getString("room");
KItem KTItem = new KasusItem(id,name,room);
kItemList.add(KTItem);
}
JSONArray data = JSONObject(response).getJSONObject("index).getJSONArray("data);
for(int i=0; i<data.length; i++){
JSONObject obj = data.getJSONObject(i);
String id = obj.getString("id");
String name = obj.getString("name");
}
This question already has answers here:
How to parse JSON 2D array using Java
(2 answers)
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
Trying to parse this type of json format in java
{
"output": "success",
"result": [
{
"id": 1,
"label": "name",
},
{
"id": 2,
"label": "name_2",
}
]
}
I am getting this type of json format, now what i want to do is check first if output.equalsIgnoreCase("success)" if true then parse the second array of result.
And this is i tried so far.
try {
JSONArray myJson = new JSONArray(response);
String status = myJson.getString(Integer.parseInt("output"));
if(status.equalsIgnoreCase("success")) {
for (int i = 0; i < myJson.length(); i++) {
JSONObject obj = myJson.getJSONObject(i);
name.add(obj.getString("label"));
}
Log.e("list" , name.toString());
}
} catch (Exception e) {
}
String responceStr = ...; // here is your full responce string
try {
JSONObject responce = new JSONObject(responceStr);
String status = responce.getString("output");
if ("success".equalsIgnoreCase(status)) {
JSONArray result = responce.getJSONArray("result");
for (int i=0; i < result.length(); i++){
JSONObject jsonPair = result.getJSONObject(i);
int id = jsonPair.getInt("id");
String label = jsonPair.getString("label");
}
}
} catch (JSONException e){
}
Integer.parseInt("123") -- is OK.
Integer.parseInt("output") -- is NOT OK.
because Integer.parseInt() parses the string representation of an integer. "output" string does not represent an integer.
The response is a JSONObject, not JSONArray (it is enclosed between curly brackets). The array is the field named result.
So change myJson to JSONObject and after checking the success field,
create a new variable
JSONArray resultArray = myJson.getArray("result");
and iterate over this instead of myJson. Also you should not discard the exception since the stacktrace could provide some hint about the problems. You can add
e.printStackTrace();
in the catch block.
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I want to display all data in Key value pair in a below JSON String.
response {
community: “worker”
communitystr: "<null>";
workspace: abs;
email: "<null>";
admin: false;
persona: "<null>";
userinfo: {
info: {
contact1: {
firstname: “jon”;
lastname: “Doe”
phone: “9885678905”;
objectname: contact;
id: 9;
};
event1: {
eventname: “party”;
description: "";
order: 6;
id: 4;
objectname: events;
};
files: {
filename: “sample”;
description: "";
order: 11;
id: 11;
objectname: files;
};
};
};
As I am new to this finding difficulty. how to get the key value in array or any other accessible format ? thanks for any help
First your json format is not correct, if you try to use JSONObject or GSON library is will throw not json type exception.
Please use a correct format of json something like this.
{
[
{
username: "somename",
userId : "1"
},
{
username: "somename2",
userId: "2"
}
]
}
General JSONObject contain JSONArray or JSONObject which you can parse it using android built in JSON.
JSONArray jsonArray = new JSONArray(yourJSONArray);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject json = jsonArray.getJSONObject(i);
String username = json.getString("username"); //here is how to get username key
}
Here is how you loop through every key and value inside your JSON object
JSONArray array = new JSONObject(result);
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
String value = jsonObject.getString(key)
Log.d(TAG,"key = "+key+" value = "+value); // always use tag in log cat for preventing confusion
}
Regardless anything you still need to have a proper format of JSON.
I have an integer value, say int id whose value i get runtime by getter function.
I want to replace this value of id in place of "VALUE" from .json like as follows
{
"id":"VALUE",
"name": "Name updated",
"description": "description Updated",
"active": false
}
I found following way to replace it if id is String,
String str = "myJson.json";
str.replace("\"VALUE\"", "\"id\"");
How can i use int id in above function with this format "\"id\"" ?
Any other solution are welcome.
EDIT:
String str = "myJson.json";
is wrong way to get json content into String.
You can do it with simple regex replace, e.g.:
public static void main(String[] args) {
String value = "{\"id\":\"VALUE\",\"name\": \"Name updated\",\"description\": \"description Updated\",\"active\": false}";
int id = 5;
value = value.replaceAll("\"VALUE\"", String.valueOf(id));
System.out.println(value);
}
Using org.json library you can assign it to JSON Object and Use the put method:
JSONObject jsonObject= new JSONObject(YOUR_STRING);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
JSONObject id= jsonArray.getJSONObject(0).getJSONObject("id");
person.put("VALUE", id);
regex replace may create some issue by replace someother matching string .
I did in following way.
To replace content of Json file need to convert contents in to String. I did this with help of following function.
public static String loadJson(String jsonFileName) throws IOException {
InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(jsonFileName);
return IOUtils.toString(stream);
}
Then declare a String variable,
String editedJson = loadJson(TEST_SET + "myJson.json");
editedJson.replace("VALUE", "" + id);
This question already has answers here:
Converting JSON data to Java object
(14 answers)
Closed 6 years ago.
I'm trying to convert a the following string so that I can get the properties out of it. I'm trying to insert these in the DB by getting their properties and then making objects out of them
[{"ParkingSpaces;;;;":"Name;CarPlate;Description;ExpirationDate;Owner"},{"ParkingSpaces;;;;":"A5;T555;Parkingspace A5;;"},{"ParkingSpaces;;;;":"A6;T666;Parkingspace A6;;"},{"ParkingSpaces;;;;":"A7;T777;Parkingspace A7;;"},{"ParkingSpaces;;;;":""}]
I got this string from a CSV file.
Anyone who has an idea on how I can approach this?
Thanks in advance.
Your code is quite messy, but it's doable. You can either use simple JSON parsing method like in the example:
final String json = "[{\"ParkingSpaces;;;;\":\"Name;CarPlate;Description;ExpirationDate;Owner\","
{\"ParkingSpaces;;;;\":\"A5;T555;Parkingspace A5;;\"},{\"ParkingSpaces;;;;\":\"A6;T666;Parkingspace A6;;\"},{\"ParkingSpaces;;;;\":\"A7;T777;Parkingspace A7;;\"},{\"ParkingSpaces;;;;\":\"\"}]";
final org.json.JSONArray jSONArray = new JSONArray(json);
for (int i = 0; i < jSONArray.length(); i++) {
final org.json.JSONObject jSONObject = jSONArray.getJSONObject(i);
final String parkingSpaces = jSONObject.getString("ParkingSpaces;;;;");
final String spaces[] = parkingSpaces.split(";");
System.out.println(Arrays.toString(spaces));
}
}
or use some bindings like Jackson.
What you have there is JSON with some semicolon separated strings in it. I wouldn't call this a CSV format at all.
You could parse the JSON to Java objects with a JSON parser like Gson, but you'll still need to pick the "columns" out of the Java object since they are not properly defined in JSON.
Something like this should work, I recommend you add more error checking than I have though:
public class DBEntry {
#SerializedName("ParkingSpaces;;;;")
#Expose
private String ParkingSpaces;
public String getParkingSpaces() {
return ParkingSpaces;
}
public void setParkingSpaces(String ParkingSpaces) {
this.ParkingSpaces = ParkingSpaces;
}
}
public static void main(String[] args) {
String json = "[{\"ParkingSpaces;;;;\":\"Name;CarPlate;Description;ExpirationDate;Owner\"},{\"ParkingSpaces;;;;\":\"A5;T555;Parkingspace A5;;\"},{\"ParkingSpaces;;;;\":\"A6;T666;Parkingspace A6;;\"},{\"ParkingSpaces;;;;\":\"A7;T777;Parkingspace A7;;\"},{\"ParkingSpaces;;;;\":\"\"}]";
// Convert JSON to java objects using the popular Gson library
Gson gson = new Gson();
Type collectionType = new TypeToken<ArrayList<DBEntry>>(){}.getType();
List<DBEntry> results = gson.fromJson(json, collectionType);
boolean header = true;
for (DBEntry result : results) {
// Ignore the header and empty rows
if (header || result.getParkingSpaces().isEmpty()) { header = false; continue; }
// Grab the columns from the parking spaces string
String[] columns = result.getParkingSpaces().split(";");
// TODO: Store this record in your database
System.out.println("New entry: " + StringUtils.join(columns, ", "));
}
}