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;
}
Related
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 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 am using this code to download a string from a website:
static public String getLast() throws IOException {
String result = "";
URL url = new URL("https://www.bitstamp.net/api/ticker/");
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
String str;
while ((str = in.readLine()) != null) {
result += str;
}
in.close();
return result;
}
When I print the result of this method, this is what I get:
{"high": "349.90", "last": "335.23", "timestamp": "1384198415", "bid": "335.00", "volume": "33743.67611671", "low": "300.28", "ask": "335.23"}
That's exactly what is shown when you open the URL. This works fine for me, but if there is a more efficient way to do this please let me know.
What I need to extract is 335.23. This number is constantly changing, but the words such as "high", "last", "timestamp", etc always stay the same. I need to extract the 335.23 as a double. Is this possible?
Edit:
SOLVED
String url = "https://www.bitstamp.net/api/ticker/";
try {
JsonFactory factory = new JsonFactory();
JsonParser jParser = factory.createParser(new URL(url));
while (jParser.nextToken() != JsonToken.END_OBJECT) {
String fieldname = jParser.getCurrentName();
if ("last".equals(fieldname)) {
jParser.nextToken();
System.out.println(jParser.getText());
break;
}
}
jParser.close();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JarException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This is JSON. Use a good parser like Jackson. There are also good Tutorials available.
The response is a json. Use a java JSON Parser and get value for "high" element.
One of the java json parsers is available on (http://www.json.org/java/index.html)
JSONObject obj = new JSONObject(" .... ");
String pageName = obj.getString("high");
The data String that you have received is known as JSON encoding. JSON (JavaScript Object Notation) is a lightweight data-interchange format. Use a fine grain simple json encoder and decoder to encode and decode data.
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