Parsing regular expression from API return - java

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.

Related

getString not working for JSON key

I'm learning how to work with JSON's in java and I'm having a problem using getString for one of my keys. My code is here:
public static void getJSON(String matchID){
String s = "";
String test = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"}]}";
try {
JSONObject hi = new JSONObject(test);
JSONArray stuff = hi.getJSONArray("employees");
String[] items = new String[stuff.length()];
items[0] = stuff.getString("firstName");
} catch (JSONException e) {
e.printStackTrace();
}
}
The "getString" is underlined in red, and the "The method getString(int) in the type JSONArray is not applicable for the arguments (String)" I was following an answer to another question word for word almost, and this happens, any advice? Thanks!
EDIT:
I need to get the specifics by name ie. "firstName" because I will be working with thousands of JSONs that each have hundreds of lines.
You need to get the JSOnObject first from the JSONArray(stuff) before you can call getString().
if you want to get the first element in the jsonarray and get its string this is how you would do it
JsonObject obj = stuff.getJsonObject(0);
String name = obj.getString("firstname");
So I figured out my problem, I didn't realize I had an JSONObject first, my apologies. Fixed like this:
JSONObject hi = new JSONObject(test);
JSONArray stuff = hi.getJSONArray("employees");
JSONObject name = stuff.getJSONObject(0);
String[] items = new String[hi.length()];
items[0]=name.getString("firstName");
System.out.println(items[0]);
you can try the simplest way to Parse in JSON
JSONParser parser=new JSONParser();
String s = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"}]}";
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println(array.get(1));
}catch(ParseException pe){
}

how to read JSON from HTTP GET request?

I have created a java server which gets HTTP GET request url as
/Star/getDetails?sentMsg=data.requestorName:ABC,data.companyName:EFG,portfolios:
[{name:,placeholder:Portfolio 1,positions:[{ticker:T1234,weight:29.85},
{ticker:T2345,weight:70.15}],active:false}],analyticsDate:20140630}
I have to parse sentMsg parameter such as I am able to read each variable individually. For eg, i should be able to read data.requestorName, companyName. I am not able to find a way to do it.
request.getParameter("sentMsg") always return String.
Tried parsing it through json-simple
JSONParser jp = new JSONParser();
try {
Object obj = jp.parse(sentMsg);
JSONArray ja = (JSONArray)obj;
} catch (ParseException e) {
e.printStackTrace();
}
But this gives parse exception. I have limitation to use json-simple jar only. Any suggestion on how to do it?
Get the paramter sentMsg from HttpRequest object store it into a string. Split from comma i.e. "," and the last second token would be the json string. You can now parse it using Json simple lib and extract values from it.
Provided you have valid JSON like:
private static String jsonString = "[{name : \"stackOverFlow\"}]";
Convert it to JSONArray like:
JSONArray jsonArray = new JSONArray(jsonString );
Then you can get value out of JSONArray by looping through it:
for (int i = 0; i < jsonArray.length(); i++) { //Iterating over mediaArray
JSONObject media = jsonArray.getJSONObject(i);
String nameFromJSON = media.getString("name");
System.out.println("Name = " + nameFromJSON);
}
Output will be:
//Name = stackOverFlow

Android Converting String to JSON [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I need advice into how to work out a method in Android which has to pick a string loaded with JSON data and then convert it back to JSON.
For the time being, I have programmed the following but I'm not sure if I'm on the right track or not.
private void convert_JSON()
{
String json;
//funcions per a cridar el string amb JSON i convertir-lo de nou a JSON
JSONArray jsas = new JSONArray();
for (int i =0; i < jsas.length(); i++)
{
JSONObject message = jsas.getJSONObject(i);
String content = message.getString("content");
}
}
The JSON is loaded into a String in this other method:
private void read_JSON(String json)
{
JSONObject jObject = new JSONObject(json);
JSONArray jso3 = new JSONArray (jObject.getString("Nombres_Hijos"));
String name = jso3.getString("Nombre");
System.out.println(name);
String surname = jso3.getString("Apellidos");
System.out.println(surname);
int date = jso3.getInt("Año_nacimiento");
System.out.println(date);
JSONArray jsa2 = jso3.getJSONArray ("Nombres_Hijos");
String names = jsa2.toString();
for (int i=0; i < jsa2.length(); i++)
{
System.out.println(jsa2.getString(i));
}
jso3.toString(json);
}
And, lastly, the JSON is created within the MainActivity.java, not as a split file yet that does work correctly:
private void create_JSON(String json)
{
JSONObject jso = new JSONObject();
try {
jso.put("Nombre","Miguel");
jso.put("Apellidos", "Garcia");
jso.put("Año_nacimiento", 1990);
JSONArray jsa = new JSONArray();
jsa.put("Blur");
jsa.put("Clur");
jso.put("Nombres_Hijos", jsa);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jso.toString();
In short: what I want to know is if my method convert_JSON is on the right track or I'm misunderstanding how it's supposed to work like.
Thank you very much for your help.
Yours sincerely,
Mauro.
You can convert a jsonstring back to json using the following JSONObject(String json) constructor:
JSONObject jsonObject = new JSONObject(jsonString);
Just, put it inside a try catch block and you should be good to go :)
You can create a JSONObject from a String using the constructor:
JSONObject json = new JSONObject(myString);
And to convert your JSONObject to a String, just use the toString() method:
String myString = json.toString();
Additionally, if you are trying to get a specific String value from the JSONObject, you can do this:
if (json.has("content"))
{
String content = json.getString("content");
//do something with content string
}
Finally, if you aren't very comfortable using JSONObject, I recommend using the tools provided by droidQuery to help you parse, such as:
Object[] array = $.toArray(myJSONArray);
and
Map<String, ?> map = $.map(myJSONObject);
If you want a pure copy/paste example have a look here
Alternatively I would suggest using one of the many well documented libraries. My personal favourite is GSON
Plenty of examples on the net on how to use this.

Java String conversion to JSON can not be done

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

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"));

Categories