'}' expected error in Java however it's already there - java

I'm trying to create a multi-dimensional array in Java and I have it set up correctly however at the end it is saying '{' expected when there's already one there. This is the error line within the code
{
"Gerald Field", "U18", "Male", "Bourges", "14.01", "26.59","50.05"
};
Any suggestions on a way to fix this problem?
Edit:
Before this line is the rest of the array and this coding:
import javax.swing.JOptionPane;
public class CMS_Program
{
public CMS_Program()
{
String[][] names = new String[][]
{
{ Array here
All { are closed off too at the end.

Lot of context is still missing from your question. Anyway, the direct initialization of a String[][] ought basically to be done as follows:
String[][] names = new String[][] {
{ "Gerald Field", "U18", "Male", "Bourges", "14.01", "26.59", "50.05" },
{ "Gerald Field", "U18", "Male", "Bourges", "14.01", "26.59", "50.05" },
{ "Gerald Field", "U18", "Male", "Bourges", "14.01", "26.59", "50.05" },
{ "Gerald Field", "U18", "Male", "Bourges", "14.01", "26.59", "50.05" },
{ "Gerald Field", "U18", "Male", "Bourges", "14.01", "26.59", "50.05" }
};
However, you're better off using a List<Person> where the Person class look like this.
public class Person {
private String name;
private String id; // ??
private Gender gender;
private String city; // ???
private Double time; // Or so?
// ...
// Add/generate c'tor/getter/setter/equals/hashcode and other boilerplate.
}
This way you can just end up with
List<Person> persons = new ArrayList<Person>();
persons.add(new Person("Gerald Field", "U18", Gender.MALE, "Bourges", 14.01, 26.59, 50.05));
// ...
Just work with real objects/entities and don't fiddle low-level with complex arrays. Your code will become more self-documented and better maintainable.

Try this:
String[][] twoDimensional = {{"00", "01"}, {"10", "11"}};

It looks like you are doing this:
String[][] names = new String[][]
{
{
"Gerald Field", "U18", "Male", "Bourges", "14.01", "26.59","50.05"
};
Note that there is a missing closing '}'
If the closing brace is not missing then the semicolon needs to be after the second closing brace and not the first.

This should work out fine.
String[][] names = new String[][]
{
{"ramalam", "wam wam"},
{"ramalam", "wam wam"}
};
Could it be that you had a semi-colon after the array?

This is valid:
String[][] names = new String[][]
{
{
"Gerald Field", "U18", "Male", "Bourges", "14.01", "26.59","50.05"
}
};
I can't see how this differs from your source though...

{ and } are the beginning and end symbols of an array, and , is used to delimit the elements in the array..
If you create a multidimensional array (basically an array of array you need to use {..} for the array that is declared, as well as for any element within, because those are arrays too.
So, use something like this:
String[][] myMultiDimensionalArray = new String[][]
{
{
"Gerald Field", "U18", "Male", "Bourges", "14.01", "26.59","50.05"
},
{
"Name Lastname", "U18", "Male", "Bourges", "14.01", "26.59","50.05"
}
}
What the error is trying to say is that it sees only one dimension, and it was let to believe that there will be two.

Related

Java - Read data from a json with the JSON library according to an object

I have a JSON with some data and I would like to print as follows
10 REGISTER 1, KP SUM 2081,606
20 REGISTER 2 CH SUM 0,22
Where the general sum is calculated by the total sum of the items according to the code.
Following the rule, first multiply the quantity by the unit and then add all the items that have the same code.
Example:
code 10
SUM = 0,0200000 * 7,40 + 10,0000000 * 200,31 + 0,5690000 * 40,19 + 0,7890000 * 70,33
The same goes for the other codes that appear in JSON
My JSON
[
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"itemCode": 1,
"descriptionItem": "ITEM",
"unityItem": "UN",
"quantity": "0,0200000",
"valueUnity": "7,40"
},
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"codeItem": 2,
"descriptionItem": "ITEM 2",
"unityItem": "UN",
"quantity": "10,0000000",
"valueUnity": "200,31"
},
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"codeItem": 88248,
"descriptionItem": "ITEM 3",
"unityItem": "H",
"quantity": "0,5690000",
"valueUnity": "40,19"
},
{
"code": 10,
"description": "REGISTER 1",
"unity": "KP",
"typeItem": "I",
"codeItem": 88267,
"descriptionItem": "ITEM 4",
"unityItem": "N",
"quantity": "0,7890000",
"valueUnity": "70,33"
},
{
"code": 20,
"description": "REGISTER 2",
"unity": "CH",
"typeItem": "I",
"codeItem": 1,
"descriptionItem": "ITEM 1",
"unityItem": "H",
"quantity": "30,0000000",
"valueUnity": "0,17"
},
{
"code": 20,
"description": "REGISTER 2",
"unity": "CH",
"typeItem": "I",
"codeItem": 2,
"descriptionItem": "ITEM 2",
"unityItem": "H",
"quantity": "3,0000000",
"valueUnity": "0,07"
}
]
My class Java
public class MyJson {
#SerializedName("code")
#Expose
private Integer code;
#SerializedName("description")
#Expose
private String description;
#SerializedName("unity")
#Expose
private String unity;
#SerializedName("typeItem")
#Expose
private String typeItem;
#SerializedName("codeItem")
#Expose
private Integer codeItem;
#SerializedName("descriptionItem")
#Expose
private String descriptionItem;
#SerializedName("unityItem")
#Expose
private String unityItem;
#SerializedName("quantity")
#Expose
private String quantity;
#SerializedName("valueUnity")
#Expose
private String valueUnity;
private Double total;
}
My Program
public static void main(String[] args) {
Gson gson = new Gson();
try {
File jsonFile = new File("C:\\my_json.json");
InputStreamReader reader = new InputStreamReader(new FileInputStream(jsonFile), "UTF-8");
BufferedReader jsonBuffer = new BufferedReader(reader);
MyJson[] myJsonArray = gson.fromJson(jsonBuffer, MyJson[].class);
BigDecimal valueUnity = BigDecimal.ZERO;
BigDecimal sumTotal = BigDecimal.ZERO;
//
Set<MyJson> list = new HashSet<>();
for(MyJson myJson : myJsonArray) {
if(checkStringNullOrEmpty(myJson.getQuantity()) && checkStringNullOrEmpty(myJson.getValueUnity())) {
if(myJson.getCode().equals(myJson.getCode())) {
String value1 = myJson.getQuantity().replaceAll( "," , "." ).trim();
String value2 = myJson.getValueUnity.replaceAll( "," , "." ).trim();
BigDecimal quantity = new BigDecimal(value1);
BigDecimal valueUnit = new BigDecimal(value2);
valueUnity = quantity.multiply(valueUnit);
somaTotal = sumTotal.add(valueUnity);
String resultado = String.format(Locale.getDefault(), "%.2f", valueUnity);
String sumTotal2 = String.format(Locale.getDefault(), "%.2f", sumTotal);
myJson.setTotal(new Double(sumTotal2.replaceAll( "," , "." ).trim()));
list.add(myJson);
}
}
}
for(MyJson myJson : list) {
StringBuilder builer = new StringBuilder();
builer.append(myJson.getCode()).append(" ");
builer.append(myJson.getDescription().toUpperCase()).append(" ");
builer.append(myJson.getUnity().toUpperCase()).append(" ");
builer.append(myJson.getTotal());
System.out.println(builer.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean checkStringNullOrEmpty(String value) {
if(!value.isEmpty()) {
return true;
} else {
return false;
}
}
Exit program
The calculation is being done wrong when using the Set
10 REGISTER 1, KP SUM 130,33
20 REGISTER 2 CH SUM 439,18
You cannot keep track of multiple running totals (i.e. one for each code) using one total. Instead you will need one total for each different code.
I would recommend that you use a Map<Integer, MyJson> for this purpose. This would store a number of MyJson objects which you could look up by their code. When handling each MyJson object, you check to see if you already have a MyJson object with the same code: if you do then you add to its total, otherwise you add your MyJson object to the map.
Get rid of your Set<MyJson> variable (which you have somewhat confusingly named list) and replace it with the following
Map<Integer, MyJson> jsonsByCode = new LinkedHashMap<>();
(You can use a HashMap<> instead of a LinkedHashMap<> here: I chose to use a LinkedHashMap<> because it keeps its entries in the same order they were inserted into it.)
Then, replace all lines from somaTotal = sumTotal.add(valueUnity); to list.add(myJson); with
if (jsonsByCode.containsKey(myJson.getCode())) {
// We've seen this code before, so add the value
// to the total.
MyJson matchingJson = jsonsByCode.get(myJson.getCode());
matchingJson.setTotal(matchingJson.getTotal() + valueUnity.doubleValue());
} else {
// First time seeing this code, so set its total
// and add it to the map.
myJson.setTotal(valueUnity.doubleValue());
jsonsByCode.put(myJson.getCode(), myJson);
}
(Note that BigDecimal values such as valueUnity have a .doubleValue() method on them, which is the easiest way to convert them to a double.)
Then, in the for loop below, where you are printing out the values, replace list with jsonsByCode.values().
I made these changes to your program and it generated the following output:
10 REGISTER 1 KP 2081.60648
20 REGISTER 2 CH 5.31
Incidentally, your code also contains the following if statement:
if(myJson.getCode().equals(myJson.getCode())) {
// ....
}
You are comparing myJson.getCode() against itself, so this condition will always be true (unless of course myJson.getCode() returns null, in which case you get a NullPointerException). You can just get rid of this check, it doesn't do anything useful.

How to print empty String Array

I'm trying to read data from .dat files & then write them in .json. The problem is some persons have no emails in files. So, I want something like
"emails": []
{
"personCode": "2342",
"firstName": "Jeff",
"lastName": "Spalding",
"address": {
"street": "123 Friendly Street",
"city": "Ottawa",
"state": "ON",
"zip": "K1A 0G9",
"country": "Canada"
},
"emails": []
},
However, my code prints no emails[]
{
"personCode": "2342",
"firstName": "Jeff",
"lastName": "Spalding",
"address": {
"street": "123 Friendly Street",
"city": "Ottawa",
"state": "ON",
"zip": "K1A 0G9",
"country": "Canada"
}
}
My code:
String[] email = null;
String[] emailTokens = data[3].split(",");
for (int i = 0; i < emailTokens.length; i++) {
email = emailTokens;
}
Person person = new Person(personCode, firstName, lastName, address, email);
personList.add(person);
Any idea? Thanks!
Your loop doesn't make sense:
for (int i = 0; i < emailTokens.length; i++) {
email = emailTokens; // Here you assign the some emailTokens N times.
}
It can be simplified to:
String[] email = data[3].split(",");
Regarding your question about missed email in the JSON, try to pass empty array:
String[] email = data[3].split(",");
if (email == null) {
email = new String[0];
}

get json data based on object name

May be it's a simple task for some one.
I've json like below.
{
"address": {
"state": "World",
"address": "infinite space, 000",
"city": "Android city",
"address2": {
"state": "World2",
"address": "infinite space2, 002",
"city": "Android city2",
"address3": {
"state": "World3",
"address": "infinite space3, 003",
"city": "Android city3"
}
}
},
"valid": {
"state": "World",
"address": "infinite space, 000",
"city": "Android city",
"valid2": {
"state": "World2",
"address": "infinite space2, 002",
"city": "Android city2",
"valid3": {
"state": "World3",
"address": "infinite space3, 003",
"city": "Android city3"
}
}
}
}
This is a sample structure. Some times may have many objects inside of one object. I know this is a bad format of JSON but i've to achieve my requirement by using this only :-(.
My requirement is: when we sending the object name like address3 or valid3 to a method as argument. My method have to return key and value of object (Which we passed as argument). Any one know, how to achieve this in Java?
You can parse the JSON and convert the result into a HashMap<String,String>
Here is sample code for this JSON object .
public HashMap<String,String> getKeyValuePairs(JSONObject json,String key){
HashMap<String,String> jsonHashList=new HashMap<String,String>();
JSONObject desiredJSON = json.get(key);
Iterator<?> keys = desiredJSON.keys();
while( keys.hasNext() ) {
String key2 = (String)keys.next();
if ( desiredJSON.get(key2) instanceof JSONObject ) {
String value = desiredJSON.get(key2);
jsonHashList.add(key2,value);
}
}
return jsonHashList;
}
Note : In this case key is assumed to be at level one of passed JSON so if you want to pass any JSON to get it's key values separated pass the Level One JSON.
This is the solution
private void parseJson(JSONObject jsonObject, String objName){
try {
for(int i = 0; i < jsonObject.length(); i++){
if(jsonObject.get(jsonObject.names().getString(i)) instanceof JSONObject){
JSONObject singleObj = new JSONObject(jsonObject.get(jsonObject.names().getString(i)).toString());
Iterator<String> keys= singleObj.keys();
while (keys.hasNext()){
String keyValue = keys.next();
final String valueString = singleObj.getString(keyValue);
if(!isJSONObjectOrString(valueString)){
if(keyValue.contains(objName) || valueString.contains(objName)
|| jsonObject.names().getString(i).contains(objName)){
Log.e("objectName", jsonObject.names().getString(i));
Log.e(keyValue, valueString);
}
}
}
parseJson(singleObj);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Dynamic parsing JSON to Java

I have problem with parsing JSON to Java. I have JSON code like that:
{
"Person 1": {
"name": "Jan",
"secname": "Kowalski",
"neighbours": {
"Person 2": {
"name": "Pawel",
"subname": "Nowak"
},
"Person 3": {
"name": "Ewa",
"subname": "Drzyzga"
}
},
"additionalInformation": {
"age": "38l",
"weight": "90kg"
}
}
}
I have only one Person in a head. He has got name, sec, name, neighbours and additionalInformation. He has 0 or more neigbours, I don't know how many. The same is with additionalInformation. With neighbours is simply because I know that every Person has only name and subname.
So I'm reading neighbours like that:
String head = "Person 1";
JSONObject obj = new JSONObject(jsonString);
Iterator iterator1 = obj.getJSONObject(head).keys();
while (iterator1.hasNext()) {
String key = (String) iterator1.next();
if (key.equals("neighbours")) {
Iterator iterator2 = obj.getJSONObject(head).getJSONObject(key).keys();
while (iterator2.hasNext()) {
String person = (String) iterator2.next();
System.out.println(obj.getJSONObject(head).getJSONObject(key).getJSONObject(person).getString("name"));
System.out.println(obj.getJSONObject(head).getJSONObject(key).getJSONObject(person).getString("subname"));
}
}
}
head can be dynamic, Person 1,2,3... but its not a problem. Problem is with recursive in that json because I don't know how additionalInformation will look like. It can be:
"additionalInformation ": {
"parents": {
"fromDad": {
"nameM": "Genowefa",
"nameD": "Jan"
},
"fromMother": {
"nameM": "Krystyna",
"nameD": "Antoni"
}
},
"weight": "90kg"
}
Is that possible to read all information in "additionalInformation"?
I have to store data like nodes because if I use method:
MODIFY "Person 1" "additionalInformation" "parents" "fromDad" "nameM" "John"
"nameM" will be change.
Is that possible? Could you tell me something about that?

Using GSON to parse a JSON array

I have a JSON file like this:
[
{
"number": "3",
"title": "hello_world",
}, {
"number": "2",
"title": "hello_world",
}
]
Before when files had a root element I would use:
Wrapper w = gson.fromJson(JSONSTRING, Wrapper.class);
code but I can't think how to code the Wrapper class as the root element is an array.
I have tried using:
Wrapper[] wrapper = gson.fromJson(jsonLine, Wrapper[].class);
with:
public class Wrapper{
String number;
String title;
}
But haven't had any luck. How else can I read this using this method?
P.S I have got this to work using:
JsonArray entries = (JsonArray) new JsonParser().parse(jsonLine);
String title = ((JsonObject)entries.get(0)).get("title");
But I would prefer to know how to do it (if possible) with both methods.
Problem is caused by comma at the end of (in your case each) JSON object placed in the array:
{
"number": "...",
"title": ".." , //<- see that comma?
}
If you remove them your data will become
[
{
"number": "3",
"title": "hello_world"
}, {
"number": "2",
"title": "hello_world"
}
]
and
Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);
should work fine.
Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);
class Wrapper{
int number;
String title;
}
Seems to work fine. But there is an extra , Comma in your string.
[
{
"number" : "3",
"title" : "hello_world"
},
{
"number" : "2",
"title" : "hello_world"
}
]
public static <T> List<T> toList(String json, Class<T> clazz) {
if (null == json) {
return null;
}
Gson gson = new Gson();
return gson.fromJson(json, new TypeToken<T>(){}.getType());
}
sample call:
List<Specifications> objects = GsonUtils.toList(products, Specifications.class);
Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);

Categories