I receive the below json as an input to my program:
{
"shopping": {
"cart": {
"items": [{
"iturl" : "https://www.google.com/",
"itdesc" : "Item’s box includes the below contents:\n a.adaptor \n b.sdfd"
}]
}
}
}
We are using jayway jsonpath to parse this data and do some processing and return the final value as a string.
when we parse it with the default jsonpath configuration, I get the iturl modified as "https:\/\/www.google.com\/"
Tried changing the JSONProvider to JacksonJsonProvider (by referring Jsonpath with Jackson or Gson) and the issue with the url is solved but, the value of itdesc is now coming to new line (due to \n) making it an invalid json.
I cannot specifically handle for each field as the incoming data will be dynamic.
Is there any proper way to parse this kind of JSON in java. Thanks in advance for your help
Try adding one more escaping level before parsing the string, the string parser's gonna give you "\n" for "\\n".
For example, parsing with Jackson ObjectMapper.
objectMapper.readValue(jsonString.replace("\\", "\\\\"), Any.class);
{
"shopping": { <-- JSONObject
"cart": { <-- JSONObject
"items": [{ <-- JSONArray
"iturl" : "https://www.google.com/", <-- JSONObject inside JSONAray
"itdesc" : "Item’s box includes the below contents:\n a.adaptor \n b.sdfd"
}]
}
}
}
if this data json come from http connection.
this json must be a string format fisrt,
and try using org.json.simple
so do like this :
private void readData() {
String Body = (response json string from connection);
JSONParser parse = new JSONParser();
String iturl = null;
String itdesc = null;
try {
JSONObject shopping = (JSONObject) parse.parse(Body);
JSONObject cart= (JSONObject) shopping.get("cart");
JSONArray items = (JSONArray ) cart.get("items ");
items.forEach((k)-> {
JSONObject inside = (JSONObject) k;
iturl = inside.get("iturl");
itdesc = inside.get("itdesc");
});
}catch ( ParseException e) {
e.printStackTrace();
}
}
if this come from file.json combine with reader :
private static final File jsonData = new File(file.json);
private void callData() {
String iturl = null;
String itdesc = null;
try {
Reader reader = new FileReader(marketList);
JSONParser parse = new JSONParser();
JSONObject shopping = (JSONObject) parse.parse(reader);
JSONObject cart= (JSONObject) shopping.get("cart");
JSONArray items = (JSONArray ) cart.get("items ");
items.forEach((k)-> {
JSONObject inside = (JSONObject) k;
iturl = inside.get("iturl");
itdesc = inside.get("itdesc");
});
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
I am trying to parse a json response so that i can get elements out of an object, getting the following error A JSONObject text must begin with '{' at 1 [character 2 line 1]
public static String parseJsonResponse(String json){
String uId ="";
try {
JSONObject jsonObj = new JSONObject(json);
// String fname = jsonObj.getString("fname");
//String lname = jsonObj.getString("lname");
String aId = jsonObj.getString("id");
uId = aId;
} catch (Exception e) {
e.printStackTrace();
}
return uId;
}
Here is json response using postman you will notice there is no header
[
{
"id": "emplo000000000043567",
"displayName": "Tester, user1",
},
{
"id": "emplo000000000035386",
"displayName": "Tester, User2",
}
]
Like the comment above mentioned, that is a JSON array so it needs to be parsed as a JSON array and not a JSON object. Just use the JSONArray equivalent provided in the library you are using.
On another note, with the JSON response above, parsing this as a JSON array would fail since the format is incorrect. Notice the comma at the end of every last keyvalue in each object. That would cause the parser to fail when attempting to parse that as a JSON array. If that was your mistake when you were writing the snippet here then ignore this paragraph. Else if that was the actual JSON response then I guess you need to make a new question... over at the Postman forum.
There are several ideas for this case.
Here is mine.
With a json simple library[link].
You can simply change your library to a json simple library which has a parser class for a json string
then use an instanceof method for detection before processing a json object.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public static String parseJsonResponse(String json){
String uId ="";
try {
JSONParser parser = new JSONParser();
Object whichone = parser.parse(json);
if(whichone instanceof JSONObject)
{
JSONObject jsonObj = (JSONObject)whichone;
// String fname = jsonObj.getString("fname");
//String lname = jsonObj.getString("lname");
if(jsonObj.containsKey("id"))
uId = (String)jsonObj.get("id");
}
else if(whichone instanceof JSONArray)
{
JSONArray jsonArr = (JSONArray)whichone;
JSONObject jsonObj = null;
for(int i = 0; i < jsonArr.size(); i++)
{
jsonObj = (JSONObject) jsonArr.get(i);
if(jsonObj.containsKey("id"))
{
uId = (String)jsonObj.get("id");
System.out.println(uId);
}
}
}
else if(whichone instanceof String)
{
System.out.println("1?????" + whichone.toString());
}
else
{
System.out.println("2?????" + whichone.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return uId;
}
Detect the object type from a json excetpion.
You can catch it whether some string is a json object or json array during exception handling.
import org.json.JSONArray;
import org.json.JSONObject;
public static String parseJsonResponse(String json){
String uId ="";
try {
JSONObject jobj = new JSONObject(json);
if(jobj.has("id"))
uId = jobj.getString("id");
System.out.println(uId);
} catch (org.json.JSONException e) {
//e.printStackTrace();
JSONArray jsonArr = new JSONArray(json);
JSONObject jsonObj = null;
for(int i = 0; i < jsonArr.length(); i++)
{
jsonObj = jsonArr.getJSONObject(i);
if(jsonObj.has("id"))
{
uId = (String)jsonObj.get("id");
System.out.println(uId);
}
}
}
return uId;
}
With a java work.
You can find it whether it's a json object or array after parsing a first character.
(I think it will work...)
import org.json.JSONArray;
import org.json.JSONObject;
public static String parseJsonResponse(String json){
String uId ="";
boolean isJobj = json.charAt(0) == '[';
if(!isJobj) {
JSONObject jobj = new JSONObject(json);
if(jobj.has("id"))
uId = jobj.getString("id");
System.out.println(uId);
} else {
JSONArray jsonArr = new JSONArray(json);
JSONObject jsonObj = null;
for(int i = 0; i < jsonArr.length(); i++)
{
jsonObj = jsonArr.getJSONObject(i);
if(jsonObj.has("id"))
{
uId = (String)jsonObj.get("id");
System.out.println(uId);
}
}
}
return uId;
}
Have a good day..
First, Your json format is wrong. The correct json format would be:
[
{
"id": "emplo000000000043567",
"displayName": "Tester, user1"
},
{
"id": "emplo000000000035386",
"displayName": "Tester, User2"
}
]
Now,
Your Response is JSON Array. So first assign parsed object into JSON Array as JSONArray array = (JSONArray) obj;
this JSON Array consists of two JSON Object so traverse the array, get each JSON Object and print/return key/value pair whatever you want.
A sample code is given below:(see the logic)
public static void parseJsonResponse(String json)
throws JsonParseException, JsonMappingException, IOException, ParseException {
String aId ="";
JSONParser parser = new JSONParser();
Object obj = parser.parse(json);
JSONArray array = (JSONArray) obj;
for(int i=0;i<array.size();i++)
{
JSONObject jsonObject = (JSONObject) array.get(i);
aId = (String) jsonObject.get("id");
System.out.println(aId);
}
}
Note: I have used json-simple java library here.
I'm trying to parse json file in my java project using this below code,
JSONParser parser = new JSONParser();
try {
Object obj = null;
try {
obj = parser.parse(new FileReader(new File("json/branch_list.json")));
} catch (org.json.simple.parser.ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject jsonObject = (JSONObject) obj;
System.out.println("Branches are :");
JSONArray listOfBranches = (JSONArray) jsonObject.get("branch_list");
Iterator iterator = listOfBranches.iterator();
for (int i = 0; i < listOfBranches.size(); i++) {
JSONObject c = listOfBranches.getJSONObject(i);
System.out.println("Branch are :" + listOfBranches.get(i));
}
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
From above code when i'm using this two below lines
JSONObject c = listOfBranches.getJSONObject(i);
String branchName = c.getString("branch_name");
Its shows the method getJSONObject(int) is undefined for the type JSONArray
And I'm getting the whole object when using this below code,
System.out.println("Branch are :"+listOfBranches.get(i));
It prints like this,
{"branch_name":"AMM"}
from this I want to get branch name using the key "branch_name". But I could not able to do this because of "the method getJSONObject(int) is undefined for the type JSONArray" exception
And I have added json-simple jar in my project. Could you please suggest me any idea to do this? Thanks in advance.
If i undestood you right then:
JSONObject item = (JSONObject)listOfBranches.get(0);
String branchName = (String)item.get("branch_name");
i think you should use org.json instead of simple-json. The method getJSONObject(i) is available in org.json. Refer to the below url for more detail.
https://stackoverflow.com/questions/2591098/how-to-parse-json
I am getting a json array as a string from one activity to the other using intent extras.How can I insert a value at a certain position in the json array in java.
This is the json array that I am using.
{"result":[{"itembarcode":"BRMS","weight":"10","gross_wt":"1","stone_amt":"0","stone_wt":"","rate":"32000","making":"100","qty":"1","net_rate":"32100.0","item_total":"32100.0","sum_total":"64600.0"},
{"itembarcode":"MSAA0015","weight":"10","gross_wt":"11","stone_amt":"100000","stone_wt":"","rate":"32000","making":"500","qty":"1","net_rate":"32500.0","item_total":"32500.0","sum_total":"64600.0"}]}
And I would like to insert a doc_no inside this array something like
{"result":[{"doc_no":"IN1001","itembarcode":"BRMS","weight":"10","gross_wt":"1","stone_amt":"0","stone_wt":"","rate":"32000","making":"100","qty":"1","net_rate":"32100.0","item_total":"32100.0","sum_total":"64600.0"},
{"doc_no":"IN1001","itembarcode":"MSAA0015","weight":"10","gross_wt":"11","stone_amt":"100000","stone_wt":"","rate":"32000","making":"500","qty":"1","net_rate":"32500.0","item_total":"32500.0","sum_total":"64600.0"}]}
I have tried something like this
try {
JSONArray jr = new JSONArray(json);
for (int j=0;j<tot_length; j++)
{
JSONObject jb = jr.getJSONObject(j);
String docnumber = "IN1001";
jb.put("doc_no",docnumber);
}
Log.d("NEW JSON",json);
} catch (JSONException e) {
e.printStackTrace();
}
But it did not work for me.
Any help or suggestion is appreciated.Thank you.
JSONObject has no support for manage ordering .. so you need to use library like GSON
i have done this using GSON ..
lets try
try {
JSONObject jsonObject = new JSONObject(yourJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for(int i=0;i<jsonArray.length();i++){
LinkedHashMap<String,String> linkedHashMap = new LinkedHashMap<>();
JSONObject innerJosonObject = new JSONObject(jsonArray.getString(i));
// you need to put all values from jsonObject to map for managing the order..
linkedHashMap.put("doc_no","Custom Value");
linkedHashMap.put("itembarcode",innerJosonObject.getString("itembarcode"));
linkedHashMap.put("weight",innerJosonObject.getString("weight"));
linkedHashMap.put("gross_wt", innerJosonObject.getString("gross_wt"));
//..................... rest of others......
linkedHashMap.put("sum_total",innerJosonObject.getString("sum_total"));
Gson gson = new Gson();
// convert linkedHashMap to json string and it will keep the insertion order..
String string = gson.toJson(linkedHashMap,LinkedHashMap.class);
jsonArray.put(i,string);
}
jsonObject.put("result",jsonArray);
Log.e("json",jsonObject.toString());
// this prints jsonArray only [............]
Log.e("json_array", jsonArray.toString());
}catch (Exception e){
}
Output:`{"result":["{\"doc_no\":\"Custom Value\",\"itembarcode\":\"BRMS\",\"weight\":\"10\",\"gross_wt\":\"1\",\"sum_total\":\"64600.0\"}",
"{\"doc_no\":\"Custom Value\",\"itembarcode\":\"MSAA0015\",\"weight\":\"10\",\"gross_wt\":\"11\",\"sum_total\":\"64600.0\"}"]}`
Add this to gradle file
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.android.support:appcompat-v7:22.2.1'
}
Hope it helps .. Thank You
You need to store the changed jsonObject again in array
try this code
CODE
try {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject1 = new JSONObject(
"{ \r\n \"itembarcode\":\"BRMS\",\r\n \"weight\":\"10\",\r\n \"gross_wt\":\"1\",\r\n \"stone_amt\":\"0\",\r\n \"s\u200C\u200Btone_wt\":\"\",\r\n \"rate\":\"32000\",\r\n \"making\":\"100\",\r\n \"qty\":\"1\",\r\n \"net_rate\":\"32100.0\",\r\n \"item_to\u200C\u200Btal\":\"32100.0\",\r\n \"sum_total\":\"64600.0\"\r\n }");
JSONObject jsonObject2 = new JSONObject(
"{ \r\n \"itembarcode\":\"MSAA0015\",\r\n \"weight\":\"10\",\r\n \"gross_wt\":\"11\",\r\n \"stone_amt\":\"100000\",\r\n \"st\u200C\u200Bone_wt\":\"\",\r\n \"rate\":\"32000\",\r\n \"making\":\"500\",\r\n \"qty\":\"1\",\r\n \"net_rate\":\"32500.0\",\r\n \"item_tot\u200C\u200Bal\":\"32500.0\",\r\n \"sum_total\":\"64600.0\"\r\n }");
jsonArray.put(jsonObject1);
jsonArray.put(jsonObject2);
JSONObject finalObject = new JSONObject();
finalObject.put("result", jsonArray);
System.out.println("Old----->" + finalObject);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
json.put("doc_no", "IN1001");
jsonArray.put(i, json);
finalObject.put("result", jsonArray);
}
System.out.println("New----->" + finalObject);
} catch (Exception e) {
e.printStackTrace();
}
Output
Old----->{"result":[{"sum_total":"64600.0","making":"100","stone_amt":"0","rate":"32000","qty":"1","weight":"10","net_rate":"32100.0","gross_wt":"1","item_to\u200c\u200btal":"32100.0","s\u200c\u200btone_wt":"","itembarcode":"BRMS"},{"sum_total":"64600.0","making":"500","stone_amt":"100000","item_tot\u200c\u200bal":"32500.0","rate":"32000","qty":"1","st\u200c\u200bone_wt":"","weight":"10","net_rate":"32500.0","gross_wt":"11","itembarcode":"MSAA0015"}]}
New----->{"result":[{"sum_total":"64600.0","making":"100","stone_amt":"0","rate":"32000","qty":"1","doc_no":"IN1001","weight":"10","net_rate":"32100.0","gross_wt":"1","item_to\u200c\u200btal":"32100.0","s\u200c\u200btone_wt":"","itembarcode":"BRMS"},{"sum_total":"64600.0","making":"500","stone_amt":"100000","item_tot\u200c\u200bal":"32500.0","rate":"32000","qty":"1","doc_no":"IN1001","st\u200c\u200bone_wt":"","weight":"10","net_rate":"32500.0","gross_wt":"11","itembarcode":"MSAA0015"}]}
EDIT I didn't realise that there is one more jsonObject:)
I am new to json so please help me to get solve this
propertyAlerts: [
{
alertDomain: "oiq.core.alert.PropertyAlert",
alertType: "HERITAGE_DETECTED",
oiqCreatedDate: "2013-11-04 03:06:26"
}]
By using java, I want to get the following data
OUTPUT:
alertDomain: "oiq.core.alert.PropertyAlert"
alertType: "HERITAGE_DETECTED"
oiqCreatedDate: "2013-11-04 03:06:26"
The following is used by me
public void checklicense(String filename) throws Exception
{
JSONParser parser=new JSONParser();
Object obj = parser.parse(new FileReader("./output_profiles/"+filename));
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonMainArr = obj.getJSONArray("propertyalert");
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String alertDomain = childJSONObject.getString("alertDomain");
}
Can any one help me to solve this problem
This tutorial explains the basics of JSON parsing.
I would recommend you to read the entire post as it is something that you will do almost daily in Android development.
public static void checklicense(String filename)
{
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(filename));
System.out.println(obj.getClass());
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonMainArr = (JSONArray) jsonObject.get("propertyAlerts");
Iterator iterator = jsonMainArr.iterator();
while(iterator.hasNext()) {
jsonObject =(JSONObject) iterator.next();
String alertDomain = (String) jsonObject.get("alertDomain");
String alertType = (String) jsonObject.get("alertType");
System.out.println("alertDomain " + alertDomain + ", alertType " + alertType );
}
} catch (Exception ex) {
java.util.logging.Logger.getLogger(EosClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
The above code produces the required output for a valid json input
{
"propertyAlerts": [
{
"alertDomain": "oiq.core.alert.PropertyAlert",
"alertType": "HERITAGE_DETECTED",
"oiqCreatedDate": "2013-11-04 03:06:26"
}
]
}