Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have this string
[23,22,17][17,2][23][3,29][][10,43,6][7][32,17,6][][][23,49,12][14,40,15][34,41,32][4,7,19][9,27][17][31,36,45][][32][40,27,25]
obtained from json and i saved it into ArrayList like this:
ArrayList<?> listAdress=(ArrayList<?>)jobj.get("adress");
I want to take only the numbers and save the numbers in brackets into a vector like this.
v[]={23,22,18}
v[]={17,2}
I tried to get only the numbers, but i dont know how to take the numbers untill you find ]
Someone know how to?
here is the regex you'll need for your problem :
(\d*,*)*
A link for explanation of this regex
here follows the java method to get the arrays of numbers :
public static List<String []> getNumberArrays (String toBeProcessed){
List<String[]> listOfArrays = new ArrayList<String[]>();
Pattern p = Pattern.compile("(\\d*,*)*");
Matcher m = p.matcher(toBeProcessed);
while(m.find()){
String[] a ;
a =m.group(0).split(",");
// next statement for avoiding the printing of empty arrays
if(a.length>=2)
listOfArrays.add(a);
}
return listOfArrays;
}
Test code :
String x = "[23,22,17][17,2][23][3,29][][10,43,6][7][32,17,6][][][23,49,12][14,40,15][34,41,32][4,7,19][9,27][17][31,36,45][][32][40,27,25]" ;
List<String[]> listOfArrays = new ArrayList<String[]>();
listOfArrays = getNumberArrays(x);
for(String[] a :listOfArrays){
System.out.println(Arrays.toString(a));
}
Output :
[23, 22, 17]
[17, 2]
[3, 29]
[10, 43, 6]
[32, 17, 6]
[23, 49, 12]
[14, 40, 15]
[34, 41, 32]
[4, 7, 19]
[9, 27]
[31, 36, 45]
[40, 27, 25]
What about this:
public static void main(String[] args) {
String testStr = "[23,22,17][17,2][23][3,29][][10,43,6][7][32,17,6][][][23,49,12][14,40,15][34,41,32][4,7,19][9,27][17][31,36,45][][32][40,27,25]";
ArrayList<String[]> result = new ArrayList<>();
String[] resTmp = testStr.split("\\[|\\]\\["); // First split input into vectors
for (String vecDef: resTmp) // Then split each vector into a String[]
result.add(vecDef.split(","));
for (String[] s : result) { // result = ArrayList with an element for each vector
for (String ss : s) // Each element is an array of Strings each being a number
System.out.print(ss + " ");
System.out.println();
}
}
I know you asked for a Regex but I'm not sure it's the only or the best way to go for such a simple parsing.
Here a quick (and not so safe) code:
public class HelloWorld{
public static void main(String []args){
String input = "[23,22,17][17,2][23][3,29][][10,43,6][7][32,17,6][][][23,49,12][14,40,15][34,41,32][4,7,19][9,27][17][31,36,45][][32][40,27,25]";
input = input.substring(1, input.length()-1);
String[] vectors = input.split("\\]\\[");
for(String vector : vectors)
{
System.out.println(String.format("\"%s\"", vector));
}
}
}
Output:
"23,22,17"
"17,2"
"23"
"3,29"
""
"10,43,6"
"7"
"32,17,6"
""
""
"23,49,12"
"14,40,15"
"34,41,32"
"4,7,19"
"9,27"
"17"
"31,36,45"
""
"32"
"40,27,25"
The thing is: you have to make sure that the string provided as an input is always well formatted (beginning with a [, ending with a ], and made of segments beginning with [ and ending with ]). Yet it's almost the same story with regular expressions (invalid input = no outputs, or partial outputs).
Once you have your strings with numbers separated by commas, the rest of the job is easy (you can split again and then parse to Integers).
public void importarCorreos() throws Exception{
#SuppressWarnings("deprecation")
ClientRequest cr = new ClientRequest("http://di002.edv.uniovi.es/~delacal/tew/1415/practica02/servicio_correos.php");
#SuppressWarnings("deprecation")
String result = cr.get(String.class).getEntity(String.class);
CorreosService service = Factories.services.createCorreosService();
//Imprimimos todo el flujo JSON recibido en formato cadena.
System.out.println(result);
//Procesamos el texto JSON y lo pasamos a formato SIMPLE-JSON
Object obj=JSONValue.parse(result);
JSONArray correos = (JSONArray)obj;
ListIterator li = correos.listIterator();
while(li.hasNext()){
JSONObject jobj =(JSONObject) li.next();
Correo c = new Correo();
c.setFechaHora( Long.parseLong(jobj.get("fechahora").toString()));
c.setAsunto(jobj.get("asunto").toString());
c.setCuerpo(jobj.get("cuerpo").toString());
c.setCarpeta( Integer.parseInt(jobj.get("carpeta").toString()));
c.setLogin_user(usuario.getLogin());
ArrayList<?> listaDestinatarios=(ArrayList<?>)jobj.get("destinatarios");
service.saveCorreo(c);
}
}
This is my function, mainly i obtained a json with mails from this url. I create a new mail with the fields from that url. But one of field from Mails class is mail_contacts where you should save the adresses from each contact like a vector [1,2,3] this is the id from the adress.
So how can i get the numbers into [ ], and save it into the fields mail_contacts what its a array.
I can save it like this:
c.setMailAdress(Here i want an array with the numbers from each [])
#ulix
Ok, this give the exit that i want:
00:53:20,413 INFO [stdout] (default task-6) 23 22 17
00:53:20,414 INFO [stdout] (default task-6) 17 2
00:53:20,414 INFO [stdout] (default task-6) 23
00:53:20,416 INFO [stdout] (default task-6) 3 29
00:53:20,416 INFO [stdout] (default task-6)
00:53:20,417 INFO [stdout] (default task-6) 10 43 6
But i want to save each position from string into an array of int, like int v[]={23,22,17}
Related
I have a Json like this:
{
"hello": {
"hello": [
{
"wwrjgn": "aerg",
"aaa": "gggg",
"rfshs": {
"segse": "segsegs",
"xx": "rgwgwgw",
"x-e ": "eergye"
},
"egg": "sgsese",
"segess": "sgeses",
"segess": "segess"
},
{
"esges": "segesse",
"segesg": "ws",
"rddgdr": {
"rdrdrdg": “srgsesees"
},
"drr": 3600,
"esese": "uytk",
"wew": "699",
"eses": “qe4ty"
}
],
"how": www"
}
}
I do the following:
Object document =
Configuration.defaultConfiguration().addOptions().jsonProvider()
.parse(ka.toJSONString());
int queries = JsonPath.read(document, "$..hello.length()");
System.out.println("THE LENGTH OF THE NUMBER OF QUERIES " + queries);
I get:
nested exception is java.lang.ClassCastException: net.minidev.json.JSONArray
cannot be cast to java.base/java.lang.Integer] with root cause
java.lang.ClassCastException: net.minidev.json.JSONArray cannot be cast to
java.base/java.lang.Integer
Trying it here: http://jsonpath.herokuapp.com/?path=$..hello.length()
I get:
[
2,
2
]
Which is what i need.
Any idea what i am doing wrong?
Thanks in advance.
This ...
JsonPath.read(document, "$..hello.length()")
... will cast its response an instance of net.minidev.json.JSONArray which cannot be cast to an int. This explains the ClassCastException
The reason you see ...
[
2,
2
]
... when trying the online evaulator is that this is the toString() for the JSONArray instance returns that String.
To get the "THE LENGTH OF THE NUMBER OF QUERIES " in code, just read the JsonPath output as a JSONArray and then get the size attribute of that type. For example:
JSONArray read = JsonPath.read(document, "$..hello.length()");
// prints:
// THE LENGTH OF THE NUMBER OF QUERIES 2
System.out.println("THE LENGTH OF THE NUMBER OF QUERIES " + read.size());
You could also return a List<Integer, for example:
List<Integer> read = JsonPath.read(document, "$..hello.length()");
// prints:
// THE LENGTH OF THE NUMBER OF QUERIES 2
System.out.println("THE LENGTH OF THE NUMBER OF QUERIES " + read.size());
Using play framework 2.0 and here goes my java code :
String queryString="SELECT watchDuration, date(startTime) from SEData";
Query query=JPA.em().createNativeQuery(queryString);
List<Object[]> resultHours = (List<Object[]>) query.getResultList();
Gson gson = new Gson();
String json = gson.toJson(resultHours);
renderJSON(json);
After browsing for a while, I did try to use Gson, which resulted me with the following output :
[[5.0,"Feb 5, 2014"],[6.0,"Feb 6, 2014"],[1.0,"Feb 7, 2014"],[2.0,"May 3, 2017"],[3.0,"May 4, 2017"]]
Since I'm fetching this data to plot on a c3.js graph, I need it in the following format :
json:[{"value":5, "date":"Feb 5, 2014"},{"value":6, "date":"Feb 6, 2014"},{"value":1, "date":"Feb 7, 2014"},{"value":2, "date":"May 3, 2017"},{"value":3, "date":"May 4, 2017"}]
OR
json: {
value:[5, 6, 1, 2, 3],
date: ["Feb 5, 2014", "Feb 6, 2014", "Feb 7, 2014", "May 3, 2017", "May 4, 2017"]
}
How can I achieve the above format retrieved MySQL database?
I doubt if my approach towards Gson is wrong, because the output that I got is not even a JSON I believe. Guide me towards the right approach if I'm not moving towards one.
Thanks.
The problem is gson doesn't know what the properties are called, so it makes an array of unnamed values.
While adding a new class will simplify things, a new class for every return type of a query means a lot of rather useless classes, especially if they are only used for marshalling.
Instead, you can map a name to each list of properties like so
HashMap<String, ArrayList<Object> > map = new HashMap<String, ArrayList<Object> >();
ArrayList<Object> values = new ArrayList<Object>();
ArrayList<Object> dates = new ArrayList<Object>();
for(int i=0; i < list.size(); i++){
values.add(resultHours.get(i)[0]);
dates.add(resultHours.get(i)[1]);
}
map.put("value", values);
map.put("date", dates);
This produces the desired output:
{
"date": ["Jan","Feb","Mar","April"],
"value": [1,2,3,4]
}
Rather than returning a list of Object[] create an object which is typed
public class ResultHours {
public int value;
public Date date;
}
and then update the getResultList();
List<ResultHours[]> resultHours = (List<ResultHours[]>) query.getResultList();
I've not tested this but in theory it should work!
I know lot of people asked similars questions but, hell I'm stuck and I don't understand why. That's weird because the JSON is valid on jsonlint :
{
"Name": "Geography",
"Questions": [{
"_question": "Where is Max?",
"_answers": ["France", "USA", "Spain", "Tunisia"],
"_correctOne": 2,
"Asked": false,
"ID": 0
}, {
"_question": "Where is the Eiffel Tower?",
"_answers": ["Marseilles", "Le Mans", "Paris", "Lyon"],
"_correctOne": 3,
"Asked": false,
"ID": 1
}, {
"_question": "Where is Barcelona?",
"_answers": ["Italy", "Germany", "Portugual", "Spain"],
"_correctOne": 4,
"Asked": false,
"ID": 2
}, {
"_question": "Where is Malibu point?",
"_answers": ["San Francisco", "San Diego", "Los Angeles", "It\u0027s just in a movie"],
"_correctOne": 3,
"Asked": false,
"ID": 3
}, {
"_question": "Where takes place the famous 24h of Le Mans?",
"_answers": ["France", "Belgium", "Canada", "Martinique"],
"_correctOne": 1,
"Asked": false,
"ID": 4
}, {
"_question": "Which one of the following countries is the biggest one?",
"_answers": ["Mexico", "USA", "Russia", "India"],
"_correctOne": 3,
"Asked": false,
"ID": 5
}, {
"_question": "Where can you find a Camel?",
"_answers": ["Siberia", "Antartic", "Artic", "Sahara"],
"_correctOne": 4,
"Asked": false,
"ID": 6
}, {
"_question": "Where can\u0027t you find the statue of the liberty?",
"_answers": ["New York", "Paris", "Las Vegas", "Strasbourg"],
"_correctOne": 2,
"Asked": false,
"ID": 7
}, {
"_question": "What did Christophe Colomb has discovered?",
"_answers": ["Europe", "America", "Africa", "Asia"],
"_correctOne": 2,
"Asked": false,
"ID": 8
}, {
"_question": "Where can\u0027t you practice sky?",
"_answers": ["Maroco", "Canada", "Norway", "Dubaï"],
"_correctOne": 1,
"Asked": false,
"ID": 9
}, {
"_question": "Which one of the following countries isn\u0027t a neighboor of the France?",
"_answers": ["Germany", "Italy", "Spain", "Portugual"],
"_correctOne": 4,
"Asked": false,
"ID": 10
}]
}
So, it's just an ArrayList<Category>. Category is the following class:
public class Category {
public String Name;
public ArrayList<Question> Questions;
}
Also, the Question class below:
public class Question {
private String _question;
private String[] _answers;
private int _correctOne;
public boolean Asked;
public int ID;
}
Everything seems alright to me, I checked again and again, still have this error. However, something seems weird, each ' is replaced by \u0027, but it doesn't seems to be the problem..
I'm parsing the Gson from the following function:
public static boolean ReadCategoryFileTxt(Category category) {
try {
File file = new File(category.Name + ".txt");
Scanner sc = new Scanner(file);
String JSONString = "";
while (sc.hasNextLine())
JSONString += sc.nextLine();
Gson gson = new Gson();
Category _category = gson.fromJson(JSONString, Category.class);
category.Name = _category.Name;
category.Questions = _category.Questions;
//Debug.Println(gson.toJson(category, Category.class));
sc.close();
}
catch (Exception e)
{
Debug.PrintException(e);
return (false);
}
return (true);
}
Any idea for this "Expected BEGIN_OBJECT but was STRING at line 1 column 4"?
Thank in advance !
Looks the start of the JSON read from file is not open flower braces {
Point 1 - See if the file has any incorrect start characters
Point 2 - Set your text file encoding to UTF -8
Point 3 - Use String Builder instead of using + append assignment
Point 4 - If you have notepad++, you shall remove non-ascii characters using - Notepad++, How to remove all non ascii characters with regex?
public static boolean ReadCategoryFileTxt(Category category) {
try {
File file = new File(category.Name + ".txt");
Scanner sc = new Scanner(file);
StringBuilder JSONString = new StringBuilder;
while (sc.hasNextLine())
JSONString = JSONString.append(sc.nextLine());
Gson gson = new Gson();
Category _category = gson.fromJson(JSONString.toString().trim(), Category.class);
category.Name = _category.Name;
category.Questions = _category.Questions;
//Debug.Println(gson.toJson(category, Category.class));
sc.close();
}
catch (Exception e)
{
Debug.PrintException(e);
return (false);
}
return (true);
}
I'd like to leave a few words based on what you clarified in the comments. To be honest, I could not reproduce the exact exception with ... line 1 column 4 having ... line 1 column 1 instead, regardless the default JVM file.encoding property, but you're faced with a classic file encoding issue.
Your JSON is really well-formed.
Java promotes some naming conventions so _question and Asked appearing in the JSON can be expressed as #SerializedName("_question") String question; and #SerializedName("Asked") boolean isAsked; respectively.
\u0027 is an escaped character of '. Characters can be unescaped if they are a part of the enclosing document encoding. The apostrophe fits ASCII just perfect, however it may be escaped in order not to break JSON documents syntactically, say, string literals in JSON strings.
The real problem was that your JSON file was not invalid characters per se, but an UTF-8 encoded file with an explicit Byte Order Mark that should be processed before parsing begins to make sure that file content encoding is detected and decoded fine ( literally stands for UTF-8). UTF-aware editors just do not show BOMs since the latter are not considered bad or illegal characters, but use them to deal with UTF-encoded files (file encoding names are usually shown in statusbars, etc). That's why copying/pasting worked for you: BOMs were not included to copies (they "live" in files only, and in clipboard metadata I guess). By default, Java classes do not make any assumptions on the incoming file encoding leaving the decision on it on your own or even on user's own. It is described here. Therefore Gson should not process it and Gson really does not do it. All Gson can only consume is JSON tokens streams (and that's perfect design), so you have either to detect the input encoding, or let your user specify it.
You don't need to accumulate an intermediate String to parse a JSON: this is just memory wasting especially for big JSON documents. Gson can work in streaming manner, so it accepts Reader instances in order not to accumulate intermediate JSON strings reading a given input stream token by token trying to consume as less memory as possible. Also note that reading line by line is cheaper with BufferedReader rather than Scanner, however it's still discouraged for you case.
If you're using Java 7 or later, use try-with-resources to make sure your I/O resources are not leaked (otherwise use finally to make sure there are no resource leaks). Also it's worth noting that instantiating a Gson instance may be considered a little expensive operation, and since Gson instances are thread-safe and immutable, they can be instantiated once per application and shared globally (not necessarily a public static final Gson ..., of course, but something encapsulated elsewhere in a good design solution).
try( final Reader reader = new InputStreamReader(new FileInputStream(new File(category.Name + ".txt")), StandardCharsets.UTF_8)) {
Category _category = gson.fromJson(reader, Category.class);
category.Name = _category.Name;
category.Questions = _category.Questions;
//Debug.Println(gson.toJson(category, Category.class));
} catch ( Exception e ) {
Debug.PrintException(e);
return (false);
}
return (true);
I have a JSON file and i am trying to deal with but the following error is appears:
Exception in thread "main" org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json.JSONObject.(JSONObject.java:195)
at org.json.JSONObject.(JSONObject.java:319)
at amazondataset.AmazonDataset.main(AmazonDataset.java:11)
Java Result: 1
This is a sample of the file:
{ "reviewerID": "A2SUAM1J3GNN3B",
"asin": "0000013714",
"reviewerName": "J. McDonald",
"helpful": [2, 3],
"reviewText": "I bought this for my husband who plays the piano. He is having a wonderful time playing these old hymns. The music is at times hard to read because we think the book was published for singing from more than playing from. Great purchase though!",
"overall": 5.0,
"summary": "Heavenly Highway Hymns",
"unixReviewTime": 1252800000,
"reviewTime": "09 13, 2009"
}
and this is my code, simply:
JSONObject ar = new JSONObject("E:\\amazonDS.json");
for (int i = 0; i < ar.length(); i++) {
System.out.println( "Name: " + ar.getString("reviewerName").toString() );
}
You have to read the content of the file first, because the constructor of JSONArray needs the file-content and not the file-path.
new JSONObject(new JSONTokener(new FileInputStream(new File("path"), "UTF-8")));
new JSONObject(new JSONTokener(new FileReader("path")));
update
You should use a filereader or specify the charset for the FileInputStream
I am new to android development and new to JSON. I am using the google maps distance matrix api. I have the JSON download into a JSONObject properly I believe.(I stole the code to do it from another post). However I can not seem to parse the JSON properly. I have been working at this for a few day and am completely stumped. I make the following call to google below
https://maps.googleapis.com/maps/api/distancematrix/json?origins=1600%20pennsylvania%20avenue&destinations=1500%20college%20street&mode=driving&units=imperial
The output is this:
{
"destination_addresses" : [ "1500 College Street, Beaumont, TX 77701, USA" ],
"origin_addresses" : [ "1600 Pennsylvania Avenue, Hagerstown, MD 21742, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1,306 mi",
"value" : 2102536
},
"duration" : {
"text" : "18 hours 48 mins",
"value" : 67684
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I have tried:
1.
JSONArray jsonArray = jObject.getJSONArray("rows");
JSONArray routes = jsonArray.getJSONArray(0);
stringBuilder.append(routes.getJSONObject(0).getString("text"));
2.
JSONArray jsonArray = jObject.getJSONArray("rows");
JSONObject routes = jsonArray.getJSONObject(0);
stringBuilder.append(routes.getJSONObject("distance").getString("text"));
3.
JSONArray jsonArray = jObject.getJSONArray("elements"); stringBuilder.append(routes.getJSONObject(0).getString("text"));
I have tried more but those seem to me like they should work. It seemed that to me rows is an array and elements is an array as well. So it would follow that I would need to get rows out of the original JSONObject then get the element array out of the row array then get the distance object out of that array, then finally get the text value and add it to the string builder I created earlier.
Were did I go wrong? thank you in advance for any help.
Here is what worked with me
//httpResponse is the output of google api
JSONObject jsonRespRouteDistance = new JSONObject(httpResponse)
.getJSONArray("rows")
.getJSONObject(0)
.getJSONArray ("elements")
.getJSONObject(0)
.getJSONObject("distance");
String distance = jsonRespRouteDistance.get("text").toString();
/*
* For distance, below is only partial solution as the
* output to string destination_addr will contain square brackets [] and double codes ""
* Eg. [ "1600 Pennsylvania Avenue, Hagerstown, MD 21742, USA" ]
*
*/
String destination_addr = new JSONObject(httpResponse)
.get("destination_addresses")
.toString();
[UPDATE]
Assuming we have only one destination address and not multiple. A little string manipulation gets us the clean string string without codes " and brackets []
StringBuilder stringBuilderDestinationAddr = new StringBuilder();
for (int i = 0; i < destination_addr.length(); i++)
if (destination_addr.charAt(i) != '[' && destination_addr.charAt(i) != ']' && destination_addr.charAt(i) != '"')
stringBuilderDestinationAddr.append(pickup_addr.destination_addr (i));
String strCleanDestination = stringBuilderDestinationAddr.toString();