This is the response I tried to parse and try to get the value in the separate strings,
response =
"Data1{
key1='4722**********6',
key2='2107',
key3=value{
value1='226',
value2=passed,
value3=tracked,
value4=noted
},
isChecked=true
}"
but unable to parse the response, like
String Datas = "Data1{key1='4722**********6', key2='2107', key3=value{value1='226',
value2=passed,value3=tracked, value4=noted}, isChecked=true}";
String data = Datas.substring(5);
//String data1 = data.replaceAll("\"", "");
try {
JSONObject dataObject = new JSONObject((data)); //JsonObject
String strKey1= dataObject.getString("key1");
String strKey2= dataObject.getString("key2");
String strKey3= dataObject.getString("key3");
JSONObject strValueObj = new JSONObject(strKey3);
String strValue1= strValueObj.getString("value1");
String strValue2= strValueObj.getString("value2");
String strValue3= strValueObj.getString("value3");
String strValue4= strValueObj.getString("value4");
Will normal String parsing work or is it correct to parse using JSON? Can anyone please help me on parse the string response.
Well, you could do some data transformations to achive JSON format:
private static final String KEY3 = "key3";
private static final String VALUE = "value";
void extractData() throws JSONException {
String Datas = "Data1{key1='4722**********6', key2='2107', key3=value{value1='226', value2=passed,value3=tracked, value4=noted}, isChecked=true}";
String data = Datas.substring(5);
String dataAsJson = data.replaceAll("=", ":");
if (dataAsJson.indexOf(KEY3) > -1) {
StringBuilder dataBuilder = new StringBuilder(dataAsJson.replaceFirst(VALUE, "{" + VALUE + ":"));
dataBuilder.insert(dataAsJson.indexOf("}", dataAsJson.indexOf(KEY3)) + KEY3.length() - 1, "}");
dataAsJson = dataBuilder.toString();
}
JSONObject dataObject = new JSONObject((dataAsJson));
String strKey1= dataObject.getString("key1");
String strKey3= dataObject.getString("key3");
JSONObject key3Obj = new JSONObject(strKey3);
String value = key3Obj.getString("value");
JSONObject valueObj = new JSONObject(value);
String value1 = valueObj.getString("value1");
}
It works but for sure is not the most elegant solution and might not work if the input would change it's structure.
Edit: new input:
String Datas = "Data1{key1='4722**********6', key2='2107', key3=value{value1='226', value2=passed,value3=tracked, value4=noted}, isMasked=true}";
String data = Datas.substring(5);
String dataAsJson = data.replaceAll("=", ":");
if (dataAsJson.contains(KEY3)) {
StringBuilder dataBuilder = new StringBuilder(dataAsJson.replaceFirst(VALUE, "{" + VALUE + ":"));
dataBuilder.insert(dataAsJson.indexOf("}", dataAsJson.indexOf(KEY3)) + KEY3.length() - 1, "}");
dataAsJson = dataBuilder.toString();
}
JSONObject dataObject = new JSONObject((dataAsJson));
String strKey1 = dataObject.getString("key1");
String strKey3 = dataObject.getString("key3");
JSONObject key3Obj = new JSONObject(strKey3);
String value = key3Obj.getString("value");
JSONObject valueObj = new JSONObject(value);
String value1 = valueObj.getString("value1");
Related
This is my JSON request body to be sent for the request endpoint
{
"id": "191",
"order":"ASC"
}
HttpPost request1 = new HttpPost("/2.0/clusters/events");
Map< String, Object >jsonValues = new HashMap< String, Object >();
jsonValues.put("id", s);
//fetching id from another API and for each id fetching the events.
JSONObject jsonO = new JSONObject(jsonValues);
request1.addHeader("Authorization",bearerToken);
request1.addHeader("content-type", "application/json");
request1.addHeader("Accept","application/json");
StringEntity entity = new StringEntity(jsonO.toString(), "UTF8");
request1.setEntity(entity);
HttpResponse response1 = client.execute(request1);
String json1 = EntityUtils.toString(response1.getEntity());
event= new JSONObject(json1);
JSONArray arrays=event.getJSONArray("events");
List<JSONObject> json_Values = new ArrayList<JSONObject>();
for (int k=0;k< arrays.length();k++){
json_Values.add(arrays.getJSONObject(k));
JSONObject ids = arrays.getJSONObject(k);
String id=clusterids.get("id").toString();
String time=clusterids.get("timestamp").toString();
String type=clusterids.get("type").toString();
System.out.println("id:" + id + "\t" + "Time:" + time + "\t" + "Type:" + type + "\n");
Collections.sort(json_Values, new Comparator<JSONObject>() {
private static final String KEY_NAME = "timestamp";
#Override
public int compare(JSONObject a, JSONObject b) {
Object valA = new Object().toString();
Object valB = new Object().toString();
valA =a.get(KEY_NAME);
valB = b.get(KEY_NAME);
return ( (String) valA).compareTo( (String) valB);
}
});
JSONArray sortedJsonArray = new JSONArray();
for (int i = 0; i < arrays.length(); i++) {
System.out.println("Sorted array:"+sortedJsonArray.put(jsonValues.get(i)));
}
}
System.out.println("EVENTS:"+arrays);
}
return event;
}
Here I am comparing the two timestamp to fetch sorted response,but I am facing some exceptions like
Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to
java.lang.String
at testdatabricks.testdatabricks.Events$1.compare(Events.java:170)
at testdatabricks.testdatabricks.Events$1.compare(Events.java:1)
Can I send json body to sort the values? How to pass that? Help me to find this out.
Are you sure you want to make a string comparison? Anyway if so then your compare method is somewhat wrong and should more look like:
Collections.sort(json_Values, new Comparator<JSONObject>() {
private static final String KEY_NAME = "timestamp";
#Override
public int compare(JSONObject a, JSONObject b) {
String valA = a.get(KEY_NAME).toString();
String valB = b.get(KEY_NAME).toString();
return valA.compareTo(valB);
}
});
just because you initialise valA as a String Object (Object valA = new Object().toString();) does not mean that val stays a String Object. When you do valA =a.get(KEY_NAME); this will not cast this to a String but it stays in the type that a.get(KEY_NAME) had before (it is exactly the same object - seemingly sometimes of type Long). But String is a nice thing - as basically all Objects that you likely encounter in a JSON have meaningful toString() implementations. So you can use that to convert everything to String and make your String comparison.
But if you timestamp is always a Long your better of with a Long-comparison:
Collections.sort(json_Values, new Comparator<JSONObject>() {
private static final String KEY_NAME = "timestamp";
#Override
public int compare(JSONObject a, JSONObject b) {
Long valA = (Long)a.get(KEY_NAME);
Long valB = (Long)b.get(KEY_NAME);
return valA.compareTo(valB);
}
});
I think your bug is here from what I can make out of the stack trace:
public int compare(JSONObject a, JSONObject b) {
Object valA = new Object().toString();
Object valB = new Object().toString();
valA =a.get(KEY_NAME);
valB = b.get(KEY_NAME);
return ( (String) valA).compareTo( (String) valB);
}
your valA and valB are Long types. And that's okay because timestamps are in long format. You need to use Long instead of String. And this is how you do it:
Long valA = Long.parseLong(String.valueOf(a.get(KEY_NAME)));
Then simply return valA.compareTo(valB);
such like this:
{aliSerialNumber=111111, pubmsCode=null, orderNumber=111, orderId=null, queryNo=null, msgId=null, consNo=null, userId=null, instId=null, companyId=null, appId=null, extendMap=null, pageSource=null, aliStatus=null}
convert into like this:
{"aliSerialNumber":"111111" ...}
is there any utils in Java I can use?
ps:The String is not a println result, it is from log:
enter image description here
You can use Gson for this.
here is sample test code to convert your string into Gson based JsonObject and verify if converted json is valid. you can use the relative following code.
#Test
public void checkJson() {
String json = "{aliSerialNumber=111111, pubmsCode=null, orderNumber=111, orderId=null, queryNo=null, msgId=null, consNo=null, userId=null, instId=null, companyId=null, appId=null, extendMap=null, pageSource=null, aliStatus=null}";
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
assertNotNull(jsonObject);
assertEquals(jsonObject.get("aliSerialNumber").getAsInt(),111111);
System.out.print(jsonObject.get("aliSerialNumber"));
}
returns true.
further read about gson here
You can do that without any utils like:
String str = "{aliSerialNumber=111111, pubmsCode=null, orderNumber=111, orderId=null, queryNo=null, msgId=null, consNo=null, userId=null, instId=null, companyId=null, appId=null, extendMap=null, pageSource=null, aliStatus=null}";
str = str.replace("{", "");
str = str.replace("}", "");
String[] temp = str.split(",");
String json = "{";
for (String s : temp)
{
String key = s.split("=")[0].trim();
String val = s.split("=")[1].trim();
json += "\"" + key + "\":";
json += "\"" + val + "\", ";
}
json = json.substring(0, json.length() - 2);
json += "}";
System.out.println(json);
Result is this (valid JSON):
{"aliSerialNumber":"111111", "pubmsCode":"null", "orderNumber":"111", "orderId":"null", "queryNo":"null", "msgId":"null", "consNo":"null", "userId":"null", "instId":"null", "companyId":"null", "appId":"null", "extendMap":"null", "pageSource":"null", "aliStatus":"null"}
My Json Response is
"results": [
[
"2C30AE32-191#Local",
"Imperva Inc.",
"SecureSphere",
"Custom Violation",
1,
"",
"KMB",
"196.207.98.94",
"10.10.1.180",
"10.10.18.14",
443,
"",
7874115,
"",
1522716763000,
"TCP",
"",
"",
""
]
]
My java Code :
String output = response.getEntity(String.class);
JSONObject obj = new JSONObject(output);
JSONArray results = obj.getJSONArray("results");
JSONArray first = (JSONArray) results.get(1);
String deviceVendor = (String) first.get(0);
String deviceProduct = (String) first.get(1);
String name = (String) first.get(2);
String baseEventCount = (String) first.get(3);
String categoryOutcome = (String) first.get(4);
String customerName = (String) first.get(5);
String sourceAddress = (String) first.get(6);
String destinationAddress = (String) first.get(7);
String deviceAddress = (String) first.get(8);
String destinationPort = (String) first.get(9);
String destinationServiceName = (String) first.get(10);
String eventId = (String) first.get(11);
String message = (String) first.get(12);
String startTime = (String) first.get(13);
String transportProtocol = (String) first.get(14);
String categoryBehavior = (String) first.get(15);
String categoryDeviceGroup = (String) first.get(16);
String categoryObject = (String) first.get(17);
Here, I am taking index number to get the data. when I am parsing it I am getting JSONArray[5] not found exception. How to handle this. if we have a json object we can handle using .has("string") but if it is json array how to handle this situation ?
I have use simplejson you can replace the net.sf.JSON
it's working.
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("C:\\Users\\user\\Desktop\\results.json"));
org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) obj;
org.json.simple.JSONArray departures = (org.json.simple.JSONArray) jsonObject.get("results");
for(int i=0;i<departures.size();i++){
System.out.println("all =="+departures.get(0));
org.json.simple.JSONArray all = (org.json.simple.JSONArray) departures.get(0);
System.out.println("test =="+all.get(5));
}
I'm converting json string to display in android textview, I'm using following code in android
My json file look likes,
{"managementlist":[{"designation":"PRESIDENT","address":"<strong>Sri<\/strong><br>M\/s.Jewellery Mart<br>No:19\/1, Raghavaiah Road,<br>T.Nagar, Chennai - 600 017.","office":"+91 44 42122288","residence":"+91 44 28341155","centrix":"2159,#421155","fax":"+91 44 42122200","mobile":"+91 9940147199","email":"jayan1411#gmail.com","image":"http:\/\/mydomain.org\/images\/ssss.jpg?1419856154","divider":"0"},{"designation":"VICE PRESIDENT","address":"<strong>Sri Yogesh J Shah<\/strong><br>M\/s. Doimands<br>\r\n "Swarna sree", shop-201,<br># 36\/2,Veerappan Street,<br> Chennai -600 079.","office":"+91 44 25385336","residence":"+91 44 26442978","centrix":"#410024","fax":"+91 44 25387772","mobile":"+91 9382616888","email":"yogesh_shah31#yahoo.co.in","image":"http:\/\/mydomain.org\/images\/Sriyogesh.jpg?1419856154","divider":"0"}]}
And my java code looks like,
public class Managements {
private String designation;
private String address;
private String officePhone;
private String residencePhone;
private String centrixNo;
private String faxNo;
private String mobileNo;
private String email;
private String image;
private int header;
get() & set();
}
Json Parser:
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
for (String line = null; (line = bufferedReader
.readLine()) != null;) {
builder.append(line);
}
String returnStr = StringEscapeUtils
.unescapeJava(builder.toString());
String s = returnStr;
JSONObject json = new JSONObject(s);
JSONArray membersarray = json
.getJSONArray("managementlist");
for (int i = 0; i < membersarray.length(); i++) {
JSONObject member = membersarray.getJSONObject(i);
Log.i("JSON OBJECT :", member.getString("mobile")
+ " , " + member.getString("divider"));
String designation = member
.getString("designation");
String address = member.getString("address");
String officePhone = member.getString("office");
String residencePhone = member
.getString("residence");
String centrixNo = member.getString("centrix");
String faxNo = member.getString("fax");
String mobileNo = member.getString("mobile");
String email = member.getString("email");
String image = member.getString("image");
int header = member.getInt("divider");
list_managements.add(new Managements(designation,
address, officePhone, residencePhone,
centrixNo, faxNo, mobileNo, email, image,
header));
}
And in my adapter
addressView.setText(Html.fromHtml(managements.get(position).getAddress()),TextView.BufferType.SPANNABLE);
But my list view display the html string as like
<strong>Sri <\/strong><br>M\/s.Jewellery Mart<br>No:19\/1, Raghavaiah Road,<br>T.Nagar, Chennai - 600 017
This code didn't convert my html string to textview, What is my mistake. Please help anyone.
you need do script like this
// Textview variable
TextView bdeskripsi = (TextView) findViewById(R.id.ddeskripsi);
// Decode htmlentities
String htmlcodeenti = Html.fromHtml(yourdatajson).toString();
// Decode tag html to webview
bdeskripsi.setText(Html.fromHtml(htmlcodeenti));
this is my json string for example :
{"data":{ "name":"Red Sox win 7-0!","famil":"INSERT TITLE HERE","tel":"2251472"}}
this is the code I write but it couldn't get the values:
JSONObject jsons = new JSONObject(myString);
Iterator<?> keys = jsons.keys();
String out = "";
while (keys.hasNext()) {
String key = (String) keys.next();
out += key + ": " + jsons.getString(key) + "\n";
}
How can I get each item's value ?
try this code.
JSONObject object = new JSONObject(myString);
JSONObject objectData = object.getJSONObject("data");
String strTel = objectData .optString("tel");
String strFamil = objectData .optString("famil");
String strName = objectData .optString("name");
In your case you can use jsons.getString(key) for each key because your JSONObject contains only Strings.
But in general, JSONObject can contain values of different types: integer, boolean, int/long, double JSONArray and JSONObject. You have to use the right .getSomething() for each one or generat .get() that retuns Object.
Great example json-simple-example-read-and-write-json