Java String conversion to JSON can not be done - java

I have JSON which I get from server:
"[{\"id\":\"1\",\"name\":\"Milos\",\"city\":\"Smederevo\",\"email\":\"milos\",\"password\":\"\"},
{\"id\":\"3\",\"name\":\"Boban\",\"city\":\"Beograd\",\"email\":\"bole\",\"password\":\"\"},
{\"id\":\"4\",\"name\":\"Pele\",\"city\":\"Brazil\",\"email\":\"pele#pele.com\",\"password\":\"\"},
{\"id\":\"5\",\"name\":\"admin\",\"city\":\"Smederevo\",\"email\":\"admin\",\"password\":\"\"}]"
I am using that json and sending to my thread (android thread):
try {
// Method from which I am getting Json described above
String s = dm.getAllUsers();
/*JSONParser jp = new JSONParser();
JsonElement jelement = new JsonParser().parse(s);
JsonArray array1 = jelement.getAsJsonArray();*/
JSONArray array = new JSONArray(s);
for (int i = 0; i < array.length(); i++) {
JSONObject menuObject = array.getJSONObject(i);
// doing something with the object
}
} catch (JSONException e) {
e.printStackTrace();
}
I can not process that Json at all.
I am getting the error "java.lang.String cannot be converted to JSONArray".
A know that problem is caused by "\", and I just do not know how to get rid of "\".
I tried:
1) s.replace("\\", "");
2) s.replace("\"", "'");
3) s.replaceAll("\\", "");
4) s.replaceAll("\"", "'");
In order to erase "\" but replace do not react at all.
I also tried to solve problem with "google-gson-2.2.2" library (code under the comment above, under the method).
Any advice, please?

Try this solution.
s.replaceAll("\\\\", "");
This will definitely work.

Problem has been solved with:
1) s = s.trim();
2) s = s.substring(1, s.length()-1);
3) s = s.replace("\\", "");
My json has been retrieved with "double quotes" on the beginning and on the end. I do not know how string variable can not figure out that "double quotes" is for "beginning" and for "ending" of string.
Thank you everybody for helping.

It is working for me...
In your json the value of "Your Json" is inclused inside "" so it's considered a string not an array..
So the solution is one of two things:
If you can modify the server response, remove the "" from arround the json array. or parse it first as string and then create a json array from that string like..
String notes = jobj.getString("GetNotesResult");
jarray = new JSONArray(notes);

I have no idea why its not working for you. Dot net web services do respond with \ but Java capable of parsing it. I did as below and it worked.
I've coded like this.
JSONArray users = null;
String jsStr = "[{\"id\":\"1\",\"name\":\"Milos\",\"city\":\"Smederevo\",\"email\":\"milos\",\"password\":\"\"},{\"id\":\"3\",\"name\":\"Boban\",\"city\":\"Beograd\",\"email\":\"bole\",\"password\":\"\"},{\"id\":\"4\",\"name\":\"Pele\",\"city\":\"Brazil\",\"email\":\"pele#pele.com\",\"password\":\"\"}, {\"id\":\"5\",\"name\":\"admin\",\"city\":\"Smederevo\",\"email\":\"admin\",\"password\":\"\"}]";
try {
users = new JSONArray(jsStr);
} catch (JSONException e) {
e.printStackTrace();
}
Log.v("JSONStr", String.valueOf(users.length()));
for(int i = 0; i<users.length(); i++){
try {
Log.v("Name", users.getJSONObject(i).getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
See the LogCat
03-18 16:34:46.459: V/JSONStr(307): 4
03-18 16:34:46.479: V/Name(307): Milos
03-18 16:34:46.479: V/Name(307): Boban
03-18 16:34:46.479: V/Name(307): Pele
03-18 16:34:46.479: V/Name(307): admin

Your json will be valid only if you remove the back slashes () in between. You could use something like:
strJson = strJson.replaceAll("\\\\", ""); OR strJson = strJson.replace("\\", ""); to remove the slashes () in between your json String. Please note that replaceAll() method treats the first argument as a regex, so you must double escape the backslash but, the replace() method treats it as a literal string, so you only have to escape it once. Please have a look at the below example for better understanding: I have kept your json text in a file named json.txt in my hard-drive for demonstration. The contents in the file looks like this:
[{\"id\":\"1\",\"name\":\"Milos\",\"city\":\"Smederevo\",\"email\":\"milos\",\"password\":\"\"},
{\"id\":\"3\",\"name\":\"Boban\",\"city\":\"Beograd\",\"email\":\"bole\",\"password\":\"\"},
{\"id\":\"4\",\"name\":\"Pele\",\"city\":\"Brazil\",\"email\":\"pele#pele.com\",\"password\":\"\"},
{\"id\":\"5\",\"name\":\"admin\",\"city\":\"Smederevo\",\"email\":\"admin\",\"password\":\"\"}]
Now the code for getting the json array:
package com.stackoverflow.com;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonTest {
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("C:/Users/sarath_sivan/Desktop/json.txt");
BufferedReader br = new BufferedReader(fileReader);
StringBuilder strJsonBuilder = new StringBuilder();
String strLine;
while((strLine = br.readLine()) != null) {
strJsonBuilder.append(strLine);
}
String strJson = strJsonBuilder.toString();
strJson = strJson.replaceAll("\\\\", ""); /*OR you can use strJson = strJson.replace("\\", "");*/
JSONArray jsonArray = new JSONArray(strJson);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject menuObject = jsonArray.getJSONObject(i);
System.out.println("id: " + menuObject.getInt("id"));
System.out.println("name: " + menuObject.getString("name"));
System.out.println("city: " + menuObject.getString("city"));
System.out.println("email: " + menuObject.getString("email"));
System.out.println("password: " + menuObject.getString("password"));
System.out.println();
// do something with your JSON
}
fileReader.close();
} catch (JSONException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

s = s.replace("\\", "");
System.out.println(s);
You need to assign your modified String back to s. This gives a proper parsable JSON.

I don't really like the various String.replaceAll(rexex, "") solutions. What if some of the strings in your JSON contain a \ as part of the information rather than the formatting? I see a 'password' field in your JSON. I don't know whether this is going to be clear text or a hash, but in the case of the former, your program might break if a user uses a backslash in their password.
What you want to do here is unescape a string. This is a problem that as far as I can tell, can't be solved with a simple regex, but it is a problem that has been solved thousands of times before. No need to reinvent the wheel.
How to unescape a string literal in java

Related

How does the JSON Parser work exactly?

Ok so I have been given a project to build a TST(Completed) and am supposed to use JSON parser on a Dictionary file to load the values into my Data structure and was given a basic class of code for example. This is the very first Time I have ever been exposed to this utility and I have absolutely no idea on how it works. Typically when I want to parse an input i would simply do something along the lines of
String[] parse = txt.split("|");
yet this obviously isn't going to work, So In the end of the code I see where it differentiates (or i think it does anyways) The Key & The Value, I need to read those line by line to feed into a another method in which I would typically do with a for Loop yet have no clue as to what syntax this method even uses
for(int i = 0; i < JSON.Size; i++) {
first = get.JSON_Key(i);
last = get.JSON_Value(i);
tst.put(key, value);
}
So obviously that would be better suited pseudo code, I don't know if this is storing separate values in separate containers and if so what to use to get a hold of those values the following is the example code we were given
public class ReadJSON
{
public static void main( String[] args )
{
String infile = "dictionary.json";
JsonReader jsonReader;
JsonObject jobj = null;
try
{
jsonReader = Json.createReader( new FileReader(infile) );
// assumes the top level JSON entity is an "Object", i.e. a dictionary
jobj = jsonReader.readObject();
}
catch(FileNotFoundException e)
{
System.out.println("Could not find the file to read: ");
e.printStackTrace();
}
catch(JsonParsingException e)
{
System.out.println("There is a problem with the JSON syntax; could not parse: ");
e.printStackTrace();
}
catch(JsonException e)
{
System.out.println("Could not create a JSON object: ");
e.printStackTrace();
}
catch(IllegalStateException e)
{
System.out.println("JSON input was already read or the object was closed: ");
e.printStackTrace();
}
if( jobj == null )
return;
Iterator< Map.Entry<String,JsonValue> > it = jobj.entrySet().iterator();//Not sure what this is doing
Map.Entry<String,JsonValue> me = it.next();//not sure what this is doing
String word = me.getKey();
String definition = me.getValue().toString();
for(int i =0; i < jsonReader.; i++) {
}
}
}
Any help in understanding this a bit more and correct syntax for that for loop would be appreciated
The code is using JSR 353: Java API for JSON Processing. Look at the https://jsonp.java.net/.

Cut a specific part of String in loop

I have a String like this:
String content = "{"begin"bf3b178a70.jpg","end",....},{"id":,"f06190e8938.jpg","end",....}"
and i want to cut out the image ID like this:
bf3b178a70.jpg
f06190e893.png
and after that, i want compose the image ID with a new url like this:
url.com/image/bf3b178a70.jpg
url.com/image/f06190e893.png
I begin with substring() to cut the first part and with content.split(""id":,"); but i have problems with a string array and normal string. I used the string array with a for-loop, because the real string is very long.
Will someone please help me?
At first blush, it looks like your string is formatted as JSON. If that's the case you can use the JSON.org Java parser or one of the many other parsers listed on the JSON.org site to break it down, or just follow the syntax diagrams they give; simple string-chopping is inadvisable since JSON is not a regular language.
I'm going to assume for the moment that you're receiving a JSON array-of-objects (square brackets around, comma separated), and that you are either reading from a file or a Web service, either of which provides an InputStream. If you have something else, you can pass a Reader or a plain String to the JSONTokener constructor, or if you have a byte array you can wrap it in a ByteArrayInputStream and pass that in.
I don't have a JDK handy to even check if this compiles :-) but here goes.
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import org.json.*;
public class ImageListProcessor
{
public static ArrayList<URL> processList(InputStream toProcess, URL baseURL)
throws JSONException, MalformedURLException
{
JSONTokener toProcessTokener = new JSONTokener(toProcess);
JSONObject toProcessResponse = new JSONObject(toProcess);
if (!toProcessResponse.isNull("error")) {
// it's an error response, probably a good idea to get out of here
throw new JSONException("Response contains error: " + toProcessResponse.get("error"));
}
JSONArray toProcessArray = toProcessResponse.getJSONArray("items");
int len = toProcessArray.length();
ArrayList<URL> result = new ArrayList<URL>(len);
for(int i = 0; i < len; i++) {
JSONObject imageRecord = toProcessArray.getJSONObject(i);
String imagePath = imageRecord.getString("image");
// if you want to remove the date portion of the path:
imagePath = imagePath.substring(1 + imagePath.lastIndexOf('/'));
URL combinedURL = new URL(baseURL, imagePath);
result.add(combinedURL);
}
return result;
}
}
Try something like this:
import java.util.regex.*;
public class ReplaceDemo {
public static void main(String[] args) {
String input =
"User clientId=23421. Some more text clientId=33432. This clientNum=100";
Pattern p = Pattern.compile("(clientId=)(\\d+)");
Matcher m = p.matcher(input);
StringBuffer result = new StringBuffer();
while (m.find()) {
System.out.println("Masking: " + m.group(2));
m.appendReplacement(result, m.group(1) + "***masked***");
}
m.appendTail(result);
System.out.println(result);
}
}

Parsing regular expression from API return

I would like to seek help on how to parse this string
{"success":false,"error":{"code":500,"message":"No keyword found."}}
I would want to be able to get the error code and the error message. The only problem I have is finding a regex that could capture the values I'm stuck at
Pattern pattern = Pattern.compile(REGEX?);
Matcher matcher = pattern.matcher(result);
You need to parse it to json and get value not regex as your response is in JSON.
JSONObject message = new JSONObject(yourResponse);
// use myJson as needed, for example
JSONObject error = message.getJSONObject(“error”);
int code = error.getInt(“code”);
String message2 = error.getString(“message”);
In Java, we do not often compile Patterns for such trivial tasks.
Quick Answer
code = Integer.parseInt(result.split("\"")[6].split(",")[0].substring(1));
msg = result.split("\"")[9].split(",")[0];
This won't work if result has commas.
if you want regex, this is it
s = s.replaceAll(".*\"code\":(.+?),.*", "$1");
The org.json library is easy to use. Example code is as below:
JSONObject obj = new JSONObject(" .... ");
int errCode= obj.getJSONObject("error").getInt("code");
This string is in json format, better use a json parser. Try this:
String s = "{\"success\":false,\"error\":{\"code\":500,\"message\":\"No keyword found.\"}}";
JSONObject jsonObject;
try {
jsonObject = new JSONObject(s);
JSONObject error = (JSONObject) jsonObject.get("error");
System.out.println(error.get("message"));
System.out.println(error.get("code"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Also have a look at this site.

Convert Json Array to Java Array

I'm trying to convert this JSON string into an array:
{"result":"success","source":"chat","tag":null,"success":{"message":"%message%","time":%time%,"player":"%player%"}}
I would like to output it like this:
<%player%> %message%
I'm very new to java, I came from PHP where you could just do somthing along the lines of:
$result = json_decode($jsonfile, true);
echo "<".$result['success']['player']."> ".$result['success']['message'];
Output: <%player%> %message%
Is there an easy way to do this in java?
I searched for some similar topics but I didn't really understand them. Could someone explain this to me like I'm 5?
Why reinvent the wheel, use GSON - A Java library that can be used to convert Java Objects into their JSON representation and vice-versa
JSON-lib is a good library for JSON in Java.
String jsonString = "{message:'%message%',player:'%player%'}";
JSONObject obj = JSONObject.fromObject(jsonString);
System.out.println("<" + obj.get("message") + ">" + obj.get("player") );
You can also use xStream for doing it which has got a very simple API. Just Google for it.
You can always use the following libraries like:
- Jackson
- GSON
Ok here is the right way to do it Without using any library:
Eg:
JSONArray jarr = api.giveJsonArr();
// giveJsonArr() method is a custom method to give Json Array.
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobj = jarr.getJSONObject(i); // Taking each Json Object
String mainText = new String(); // fields to hold extracted data
String provText = new String();
String couText = new String();
String fDatu = new String();
try {
mainText = jobj.getString("Overview"); // Getting the value of fields
System.out.println(mainText);
} catch (Exception ex) {
}
try {
JSONObject jProv = jobj.getJSONObject("Provider");
provText = jProv.getString("Name");
System.out.println(provText);
} catch (Exception ex) {
}
try {
JSONObject jCou = jobj.getJSONObject("Counterparty");
couText = jCou.getString("Value");
System.out.println(couText);
} catch (Exception ex) {
}
try {
String cloText = jobj.getString("ClosingDate");
fDatu = giveMeDate(cloText);
System.out.println(fDatu);
} catch (Exception ex) {
}
}
As you see you have many alternatives. Here is a simple one from json.org where you find lots of other alternatives. The one they supply them selves is simple. Here is your example:
String json = "{\"result\":\"success\",\"source\":\"chat\",\"tag\":null,\"success\":{\"message\":\"%message%\",\"time\":%time%,\"player\":\"%player%\"}}";
JSONObject obj = new JSONObject(json);
JSONObject success = obj.getJSONObject("success");
System.out.println("<" + success.get("player") + "> "
+ success.get("message"));

Convert a JSON string to a Java/Python (Jython) object?

So I understand that you can convert JSON strings to strings and handle JSON objects in general through the org.json bundle in Android, but here's my current situation:
I need to take a JSON string from a certain URL (I'm already able to successfully do this) and make it into an array. Well actually two arrays. The framework I'm using runs on Python and returns a dict that contains lists (arrays in Python). However, it is displayed as a JSON object. Here's an example of what I would be getting from the URL to my Java code:
{"keywords": ["middle east", "syria"], "link": [["middle east", "http://www.google.com/#q=middle east"], ["syria", "http://www.google.com/#q=syria"]]}
As you can see, it's a dict of two indices. The first one is "keywords" that has a list and the second one is "link" that contains a list of lists. The two lists (the first one and the second multidimensional one) are what I want to be able to manipulate in Java. I'm aware that you can use JSONArray, but the problem is that the arrays are stored in a Python dict, and my Android application does not properly make a JSONArray. Do you guys have any ideas of how I can handle this? I'm pretty lost. Here is my code for getting the actual JSON string (the URL in the code is not accessible to everyone, it's being served by paste on my machine):
static public void refreshFeed(){
try{
String url = "http://192.17.178.116:8080/getkw?nextline="+line;
line++;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String input = null;
try {
while ((input = reader.readLine()) != null) {
sb.append(input + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String enter = sb.toString();
feedEntry add = new feedEntry(enter);
addNewEntry(add);
in.close();
} catch(MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please also note that this is without the JSONString being made into a JSONArray. It simply translates the JSON object into a regular String that is added to a "feedEntry" object.
Mapping a python dict to a json array is ... more work than you'd expect. It'd be better to make it into either a json object or start with a list, which can be mapped straight to a json array. Info on serializing between python and java.
Here's a code example where I create a list structure in Python, and then grab it in an Android application:
#!/usr/bin/python
print "Content-type: text/html\n\n"
import json
from collections import defaultdict
mystuff = list()
mystuff.append( ('1', 'b', 'c', 'd') )
mystuff.append( ('2', 'f', 'g', 'h') )
stufflist = list()
for s in stufflist:
d = {}
d['a'] = s[0]
d['b'] = s[1]
d['c'] = s[2]
d['d'] = s[3]
stufflist.append(d)
print json.write(stufflist)
And in Android:
// Convert the string (sb is a string butter from the http response) to a json array.
JSONArray jArray = new JSONArray(sb.toString());
for(int i = 0; i < jArray.length(); i++){
// Get each item as a JSON object.
JSONObject json_data = jArray.getJSONObject(i);
// Get data from object ...
Int a = json_data.getInt("a");
String b = json_data.getString("b");
String c = json_data.getString("c");
String d = json_data.getString("d");
// Do whatever with the data ...
}

Categories