How to Post Json Data In Servlet? - java

I have a json data which can be something like:
1st json data
[
{
"id_form_delegate": "1",
"nama_merchant": "MATAHARI BARU SERASI",
"kota_merchant": "BALI",
"alamat_merchant": "JL PAKUBUWONO 2D",
"province_merchant": "BALI",
"mid_merchant": [
"112000902755",
"112000902754"
],
"tid_merchant": [
"2431002547",
"2531016215"
]
}
]
or something like
2nd json data
[
{
"id_form_delegate": "1",
"nama_merchant": "MATAHARI BARU SERASI",
"kota_merchant": "BALI",
"alamat_merchant": "JL PAKUBUWONO 2D",
"province_merchant": "BALI",
"mid_merchant": "112000902755",
"tid_merchant": "2431002547"
}
]
This my servlet code
JSONArray arrMid = jsonObject.getJSONArray("mid_merchant");
mid = new String[arrMid.size()];
JSONArray arrTid = jsonObject.getJSONArray("tid_merchant");
tid = new String[arrTid.size()];
//
System.out.println("nama_merchant: " + nama_merchant);
System.out.println("kota_merchant: " + kota_merchant);
System.out.println("alamat_merchant: " + alamat_merchant);
System.out.println("province_merchant: " + province_merchant);
System.out.println("mid: " + mid.length);
System.out.println("tid: " + tid.length);
if post 1st data result success, but if I post 2nd data I've Got error
this my error logs
net.sf.json.JSONException: JSONObject["mid_merchant"] is not a
JSONArray. net.sf.json.JSONException: JSONObject["tid_merchant"] is
not a JSONArray.
how to get value mid_merchant.length & tid_merchant.length using JSONArray
Thanks

The problem is that mid_merchant isn't an array in the second case, so you can't use JSONArray to get it's length because it has no length, it's just a String. You could send an array with only one value:
"mid_merchant": ["112000902755"],
or, if that's not what you want, you can check if it is an array (or even capture that exception) and get the String value with the getString method if it's not an array:
String stringMid = jsonObject.getString("mid_merchant");

You can use method get(String field) and check type of result:
Object node = jsonObject.get("mid_merchant");
String[] mid;
if (node instanceof JSONArray) {
mid = new String[((JSONArray) node).size()];
} else {
mid = new String[1];
}
or one-liner:
String[] mid = new String[node instanceof JSONArray ? ((JSONArray) node).size() : 1];

Try the following code
JSONArray arrMid=json.getJSONArray("mid_merchant");
String mid=arrMid.getJSONOBJECT.getJSONObject(0).getString("mid_merchant");
JSONArray tidMid=json.getJSONArray("tid_merchant");
String mid=tidMid.getJSONOBJECT.getJSONObject(0).getString("tid_merchant");

Related

Easiest way to parse a triple nested JSON?

I am given a JSON that will come in this format:
"template":{
"mod1":[
{
"param1":"55",
"param2":"5",
"param3":"somedata"
}
],
"mod2":[
{
"param1":"somedata",
"param2":"somedata"
}
],
"mod3":[
{
"param1":"somedata",
"param2":"somedata",
"param3":"somedata"
}
],
"mod4":[
{
"param1":"somedata",
"param2":"somedata"
}
],
"mod5":[
{
"param1":"somedata"
}
]
}
}
What is the easiest way to parse it? What I'd like is to get the params inside the mod and their associated values together, to store into a database. The way I am doing it is as so:
JSONObject obj = new JSONObject(json);
System.out.println(obj);
Iterator<String> keys = obj.keys();
while(keys.hasNext()) {
String key = keys.next();
JSONObject currTemplate = (JSONObject) obj.get(key);
if(currTemplate instanceof JSONObject) {
System.out.println("LIST OF ALL MODULES : " + currTemplate);
Iterator<String> currObjKeys = ((JSONObject) currTemplate).keys();
while(currObjKeys.hasNext()) {
String currObjKey = currObjKeys.next();
System.out.println("MODULE: " + currObjKey);
JSONArray array = currTemplate.getJSONArray(currObjKey);
System.out.println("ARRAY: " + array);
for(int i = 0; i < array.length(); i++){
JSONObject object = array.getJSONObject(i);
String[] names = JSONObject.getNames(object);
for(String name: names) {
System.out.println("PARAMS");
System.out.println(name);
System.out.println(object.get(name));
}
}
}
}
And it currently prints what I need correctly. What I am asking is if there is a more efficient way to do it - the way I currently have it is O(N^4), and I was wondering if anyone had any idea to parse the JSON in a more efficient way. Note: the params will not always be in form param1, param2, the names will always be different. Just changed it for confidentiality sake.
Thank you in advance.

Parse JSON string in Java without keys

I am new to parsing JSON in java. I have this JSON string:
[
{
"projectId":5,
"userName":"clinician",
"projectName":"r",
"projectSummary":"r",
"projectLanguage":"r",
"contactPersonName":"r",
"contactPersonCV":"r",
"contactPersonEmail":"r",
"contactPersonPhone":"r"
},
[
{
"consentFileId":2,
"projectId":5,
"consentDescription":"r",
"consentFileName":"test.pdf",
"servicePathToGetConsentPdf":null
},
{
"consentFileId":3,
"projectId":5,
"consentDescription":"rrr",
"consentFileName":"test.pdf",
"servicePathToGetConsentPdf":"localhost:8080/4c_viewFile?consentFileId=3"
}
],
[
{
"anonymized_patient_identifier":"r",
"projectId":5
},
{
"anonymized_patient_identifier":"2",
"projectId":5
},
{
"anonymized_patient_identifier":"5",
"projectId":5
}
]
]
I have managed to get values from simpler JSON strings but this one has multiple levels and also there is no key in each level. I tried with simple code like this:
Object obj = parser.parse(data);
JSONObject jsonObject = (JSONObject) obj;
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
but I get the error [java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject] And also I don't understand how I will get the values in lower level without a key. I tried also to save it as a JSONArray but it didn't work.
your root of json is type of JSONArray,
the first object stored in the root array is an object, you can retrieve it by using index = 0 .
this is a hack to make your code work:
JSONArray jsonArray = JSONArray.fromObject(data);
JSONObject jsonObject=obj.getJSONObject(0);
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
NOTE:
to convert a String to JSONArray, you can do :
JSONArray array = JSONArray.fromObject(data);
To improve on nafas answer, I would do this to see all the objects in the array:
Object obj = parser.parse(data);
JSONArray jsonArray = (JSONArray) obj;
for (int i = 0; i < jsonArray.size (); i++) {
JSONObject jsonObject=obj.getJSONObject(i);
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
}

Parse Json array without keys

I want to parse an array from Server but I can't obtain the array
Here is the jsonString Successfully got :
{
"status":"OK",
"message":"this is your start and end coordinates",
"data":"{\"start\":[\"35.778763\",\"51.427360\"],\"end\":[\"35.768779, 51.415002\"]}"
}
I want the Double Values from data arraylist:
//try/catch
Log.d(TAG, "Passes here");
JSONObject jObject = new JSONObject(jsonString);
JSONArray jData = jObject.getJSONArray("data");
Log.d(TAG, "Not PAASING HERE !!! ");
JSONArray jArrayStart = (JSONArray) jData.get(0);
JSONArray jArrayEnd = (JSONArray) jData.get(1);
latitudeStart = (Double) jArrayStart.get(0);
longtitudeStart = (Double) jArrayEnd.get(1);
latitudeEnd = (Double) jArrayEnd.get(0);
longtitudeEnd = (Double) jArrayEnd.get(1);
What you're trying to parse, is a string.
{
"status": "OK",
"message": "this is your start and end coordinates",
"data": "{\"start\":[\"35.778763\",\"51.427360\"],\"end\":[\"35.768779, 51.415002\"]}"
}
So it works like this:
//first, retrieve the data from the response JSON Object from the server
JSONObject response = new JSONObject(jsonString);
String status = response.getString("status");
String message = response.getString("message");
//Note this: "data" is a string as well, but we'll have to parse that later.
String data = response.getString("data");
//get the doubles from the arrays from the "data" component.
JSONObject dataObject = new JSONObject(data);
JSONArray start = dataObject.getJSONArray("start");
JSONArray end = dataObject.getJSONArray("end");
for (int i = 0; i < start.length(); i++) {
String value = start.getString(i);
//do something with the start String (parse to double first)
}
for (int i = 0; i < end.length(); i++) {
String value = end.getString(i);
//do something with end String (parse to double first)
}
So data is actually a String, but represents a JSONObject (which you'll have to parse), which, in its turn, contains two JSONArrays.
If data was a JSONObject instead of a String, the JSON would have looked like this:
{
"status": "OK",
"message": "this is your start and end coordinates",
"data": {
"start": [
"35.778763",
"51.427360"
],
"end": [
"35.768779", //note that in your example, this quote is missing (first quote on next line too)
"51.415002"
]
}
}
The value of data is not a JSONArray its JSONObject
Explanation
JSONObject will be surrounded by {}
JSONArray will be surrounded by []
data is not an array, it is a json object and therefore you can not access it the way you are doing.
If you want to fetch start array from json object "data" then use below
jObject.optJSONObject("data").optJSONArray("start");
same thing can be used to retrieve "end" json array.
then use optJSONObject() and/or optString() API to retrieve required value from json array.

Parsing JSON Data (Android)

Alright. I have a JSON Object sent to me from a server which contains the following data:
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
}
The data I want to get is the status for the three status values. Data1, data2, and data3 always show up in that order, so I'm now trying to grab the data by index (e.g. data1 = index 0, data2 = index 1, data3 = index 2). How do I do that?
Try following:
String stat1;
String stat2;
String stat3;
JSONObject ret; //contains the original response
//Parse to get the value
try {
stat1 = ret.getJSONArray("results").getJSONObject(0).getString("status");
stat2 = ret.getJSONArray("results").getJSONObject(1).getString("status");
stat3 = ret.getJSONArray("results").getJSONObject(2).getString("status");
} catch (JSONException e1) {
e1.printStackTrace();
}
You would use JSONObject and JSONArray, the entire string is one JSONObject so you would construct one with it.
JSONObject object = new JSONObject(YOUR_STRING_OF_JSON);
Then you can access it with different get methods depending upon your expected type.
JSONArray results = object.getJSONArray("result"); // This is the node name.
String status = object.getString("status");
for (int i = 0; i < results.length(); i++) {
String resultStatus = results.getJSONObject(i).getString("status");
String type = results.getJSONObject(i).getString("type");
Log.w("JSON Result #" + i, "Status: " + resultStatus + " Type: " + type);
}
You need to surround it with a try/catch because JSON access can throw a JSONException.
Try re-factoring via a forEach loop
var testData =
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
};
var output = new Object;
var resultSet = new Object;
resultSet = testData.result;
resultSet.forEach(function(data)
{
theStatus = data['status'];
theType = data['type']
output[theType] = theStatus;
});
console.log( output['data1'] );
If you've got your models setup to mirror that data set, then you can let GSON (https://code.google.com/p/google-gson/) do a lot of your work for you.
If you want a bit more control, and want to parse the set yourself you can use JSONObject, JSONArray. There's an example of parsing and assembling a json string here: Android create a JSON array of JSON Objects

Parsing JSON, not sure on how and when to use iterators (Android Platform)

I have this JSON to parse
{"files_informations": {
"row":{"value":"artist1"},
"row":{"value":"artist2"}
}
}
I would like to know how can I get the first value artist1 and then the second one artist2
This is what I am doing :
JSONObject myObject = jObject.getJSONObject("files_informations");
JSONObject rowObject = myObject.getJSONObject("row");
Iterator<JSONObject> rowIt = rowObject.keys();
while (rowIt.hasNext()) {
JSONObject tmp = rowIt.next();
Log.e("", tmp.getString("value"));
}
I got java.lang.classCastException for this JSONObject tmp = rowIt.next();
So there are my two questions :
Do I need to use iterators in this
case ?
How do one should use them ?
Edit :
Should the JSON looks like this ?
{"files_informations": [
"row":{"value":"artist2"},
"row":{"value":"artist1"}
]
}
rowIt.next() is "row" String in this case.
Refactor your JSON to this:
{"files_informations":
[ {"value":"artist2"},
{"value":"artist1"} ] }
Or even this:
{ "files_informations": [ "artist2", "artist1" ] }
and then use:
JSONArray artistsArr = myObject.getJSONArray("files_informations");
for (int i = 0; i < artistsArr.size(); i++) {
// first case
Log.d(TAG, artistsArr.get(i).getString("value"));
// Second case
Log.d(TAG, artistsArr.getString(i));
}
Iterators are not supported in JSONArrays, however you can convert them to plain Java arrays/lists if you really need it.

Categories

Resources