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();
}
}
Related
I'm trying to read/write a json file. But after the first write the json is escaped and reading it again doesn't work. I have the following json structure but with a lot more value :
{
"events": {
"XdQKixgtraz17eDHb6OW": {
"department": "Côte-d'Or",
"objectName": "Dijon",
"uid": "PMhzfzWlm6vN2yL1kY2i"
}
}
}
Here is how i build my json string :
JSONObject eventsJsonObject = new JSONObject();
JSONObject eventsData = new JSONObject();
for(Event event: eventsList){
String eventString = gson.toJson(event);
eventsData.put(event.getUid(), eventString);
}
eventsJsonObject.put("events", eventsData);
writeFile(filename, eventsJsonObject.toString());
I end up with a string looking like this and i can't read it again .. :
{"events":{"XdQKixgtraz17eDHb6OW":"{\"department\":\"Côte-d'Or\",\"objectName\":\"Dijon\",\"uid\":\"PMhzfzWlm6vN2yL1kY2i\"}"}}
As you can see there is a quote before the third semi colon that shouldn't be there. How can i correctly build my json string ?
Thanks for your time.
Edit : The error came from where i build my json string to write in file so i have rewrite my question.
Try this code
public static JSONObject readJSONFile (String path, Context context) {
String jsonStr = null;
try {
InputStream is = getActivity().getAssets().open(path);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
jsonStr = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
JSONObject jsonObj = new JSONObject((jsonStr ));
return jsonObj;
}
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 am trying to convert json file into csv file and I am using following code for that
public File convert(File toConvert) {
// TODO Auto-generated method stub
String JsonString = "{\"value\": [{\"name\",\"kind\":\"url\":]}";
JSONParser file = new JSONParser();
Object obj = file;
JSONObject jsonfile = (JSONObject) obj; //JSONObject from map interface
String name = (String) jsonfile.get("name");
System.out.println(name);
String kind = (String) jsonfile.get("kind");
System.out.println(kind);
JSONArray url = (JSONArray) jsonfile.get("url"); //JSONArray from list interface
Iterator<String> iterator = url.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
return toConvert ;
}
and my json file has a huge data and it looks like this
{
"value":[
{
"name":"accountleadscollection","kind":"EntitySet","url":"accountleadscollection"
},{
"name":"accounts","kind":"EntitySet","url":"accounts"
},{
"name":"activitymimeattachments","kind":"EntitySet","url":"activitymimeattachments"
},{
"name":"activityparties","kind":"EntitySet","url":"activityparties"
},{
"name":"activitypointers","kind":"EntitySet","url":"activitypointers"
},{
"name":"annotations","kind":"EntitySet","url":"annotations"
},{
"name":"annualfiscalcalendars","kind":"EntitySet","url":"annualfiscalcalendars"
},{...............
whenever I am trying to execute the code i am getting this error,Exception in thread "main" java.lang.ClassCastException. Is the logic I am following is correct or can anyone provide a better code for that, and I am implementing an interface which is having this method.
Convert the String in JSONObject.
Get the Array in the JSONObject by using the method getJSONArray("arraName").
If the array consist of Object then Iterate the array and then get the object using the index using method getJSONObject(index).
Now get the value using the key.
Here is the sample code in which you can do this.
Parse JSON from the string:
public void convert() throws JSONException {
String jsonString = readFile("prop.json"); //URL of your json file
JSONObject jsonObj = new JSONObject(jsonString);
JSONArray jsonArr = jsonObj.getJSONArray("value");
for (int j = 0; j < jsonArr.length(); j++) {
JSONObject tempJsonObj = jsonArr.getJSONObject(j);
System.out.println(tempJsonObj.get("name"));
System.out.println(tempJsonObj.get("kind"));
System.out.println(tempJsonObj.get("url"));
}
}
Read JSON file:
public String readFile(String filename) {
String result = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
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"
}
]
}
i have a problem which i cant solve for days.
the String line input is "{"name":"John", "Hobby":"Cycle"}" sent from a JSON from PHP server
The code at android application
public void testFn()
{
try {
while ((line = reader.readLine()) != null) {
String tmp = gson.toJson(line.toString());
JSONObject jobj = (JSONObject)new JSONParser().parse(tmp);
sb.append(jobj.get(1).toString() + "\n");
}
}catch ....
}
i wanted to convert the string received and convert it to a JSONObject / JSONArray which i can retrieve it or display to TextView as a String format. but i keep getting the error of CastException from java.String to JSON.simple.JSONObject..
Hope someone could enlighten me on this
class MyJsonObject{
private String name;
private String Hobby;
MyJsonObject() {
}
}
MyJsonObject obj = new MyJsonObject();
Gson gson = new Gson();
String json = gson.toJson(obj);
(Deserialization)
MyJsonObject obj2 = gson.fromJson(json, MyJsonObject.class);
Try
String str = "{\"name\":\"John\", \"Hobby\":\"Cycle\"}";
//i wrote preceded "\" to very " because it is code format string,
//not came from internet. You can pass direct response from PHP server
try {
JSONObject json = new JSONObject(str);
Log.d("Home",json.getString("name"));
Log.d("Home",json.getString("Hobby"));
} catch (JSONException e1) {
e1.printStackTrace();
}
Basically now i edited my code here
String line = "{"name":"John","Hobby":"Cycle"}";
Object obj=parser.parse(line);
JSONArray array=(JSONArray)obj;
JSONObject obj2 = (JSONObject)array.get(0);
System.out.println(obj2.get("name").toString());
sorry i figured out a way.
Output:
John