userDSSR
userDSSR

Reputation: 657

JSON formatting for a Java Server

I am trying to read JSON string using gson into a Java program. In the sample code below - the Java program has 3 object classes. The data in the json string will have a variable number of object instances of each class. I have tried to create a sample JSON - to parse .. but had problems parsing the various objects.

Is this the right way to consume a json string or can it be done in a different way.. How would you parse a json with variable objects of different classes. Thanks,

package newpackage;
import java.util.ArrayList;

import com.google.gson.Gson;

public class jsonsample {



public static void main(String[] args) {

    String jsonstring = "{'TableA':[{'field_A1':'A_11'},{'field_A1':'A_12'}]}"
            + ",{'TableB':[{'field_B1':'B_11','field_B2':'B_12','field_B3':['abc','def','ghi']},"
            + "{'field_B1':'B_21','field_B2':'B_Field22','field_B3':['mno','pqr','xyz']}]"
            + ",{'TableC':[{'field_C1':'C_11','field_C2':'C_12','field_C3':'C_13'},"
            + "{'field_C1':'C_21','field_C2':'C_22','field_C3':'C_23'},{'field_C1':'C_31','field_C2':'C_32','field_C3':'C_33'}]}";
    jsonstring = jsonstring.replace('\'', '"');



}

public class TableA {
    String field_A1;

    public TableA(String a){
        this.field_A1 = a;
    }

    @Override
    public String toString() {
        return ("Table A" + " " + this.field_A1);
    }

}

public class TableB {
    String field_B1;
    String field_B2;
    ArrayList<String> field_B3 = new ArrayList<String>();

    public TableB(String a, String b, ArrayList<String> c){
        this.field_B1 = a;
        this.field_B2 = b;
        this.field_B3 = c;
    }

    @Override
    public String toString() {
        return ("Table B" + " " + this.field_B1+ " " + this.field_B2);
    }

}

public class TableC {
    String field_C1;
    String field_C2;
    String field_C3;

    public TableC(String a, String b, String c){
        this.field_C1 = a;
        this.field_C2 = b;
        this.field_C3 = c;
    }

    @Override
    public String toString() {
        return ("Table C" + " " + this.field_C1 + " " + this.field_C2 + " " + this.field_C3);
    }

}

}

Upvotes: 1

Views: 299

Answers (3)

userDSSR
userDSSR

Reputation: 657

This is the code - that works based on @hurricane suggestion.

package newpackage;
import java.util.List;
import com.google.gson.*;
public class jsonsample {

public static void main(String[] args) throws ClassNotFoundException {

    String jsonstring = "{'TableA':["
            + "{'field_A1':'A_11'},"
            + "{'field_A1':'A_12'}"
            + "],"
            + "'TableB':["
            + "{'field_B1':'B_11','field_B2':'B_12','field_B3':['abc','def']},"
            + "{'field_B1':'B_21','field_B2':'B_22','field_B3':['mno','xyz']}"
            + "],"
            + "'TableC':["
            + "{'field_C1':'C_11','field_C2':'C_12','field_C3':'C_13'},"
            + "{'field_C1':'C_21','field_C2':'C_22','field_C3':'C_23'}"
            + "]}";

    jsonstring = jsonstring.replace('\'', '"');

    RootObject root = new GsonBuilder().create().fromJson(jsonstring, RootObject.class);

    for (int i=0; i < root.TableA.size(); i++){
        System.out.println(root.TableA.get(i));
    }

    for (int i=0; i < root.TableB.size(); i++){
        System.out.println(root.TableB.get(i));
    }

    for (int i=0; i < root.TableC.size(); i++){
        System.out.println(root.TableC.get(i));
    }
}
public class TableA
{
    public String field_A1;

    @Override
    public String toString() {
        return ("Table A" + " " + this.field_A1);
    }
}
public class TableB{
    public String field_B1;
    public String field_B2;
    public List<String> field_B3;

    @Override
    public String toString() {
        return ("Table B" + " " + this.field_B1 + " " + this.field_B2 + " " +  this.field_B3);
    }
}
public class TableC{
    public String field_C1;
    public String field_C2;
    public String field_C3;

    @Override
    public String toString() {
        return ("Table C" + " " + this.field_C1 + " " + this.field_C2  + " " +  this.field_C3);
    }
}
public class RootObject{
    public List<TableA> TableA; 
    public List<TableB> TableB; 
    public List<TableC> TableC; 

}

}

The output for the above is:

Table A A_11
Table A A_12
Table B B_11 B_12 [abc, def]
Table B B_21 B_22 [mno, xyz]
Table C C_11 C_12 C_13
Table C C_21 C_22 C_23

Upvotes: 0

Lars Gendner
Lars Gendner

Reputation: 1982

Your JSON-string seems incorrect to me. Let me propose the following:

public static void main(String args[]) {
    String jsonstring = "["
        + "{'TableA':[{'field_A1':'A_11'},{'field_A1':'A_12'}]}"
        + ",{'TableB':[{'field_B1':'B_11','field_B2':'B_12','field_B3':['abc','def','ghi']},"
        + "{'field_B1':'B_21','field_B2':'B_Field22','field_B3':['mno','pqr','xyz']}]}"
        + ",{'TableC':[{'field_C1':'C_11','field_C2':'C_12','field_C3':'C_13'},"
        + "{'field_C1':'C_21','field_C2':'C_22','field_C3':'C_23'},{'field_C1':'C_31','field_C2':'C_32','field_C3':'C_33'}]}"
        + "]";
    jsonstring = jsonstring.replace('\'', '"');

    Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    JsonArray array = parser.parse(jsonstring).getAsJsonArray();

    for (JsonElement jsonElement : array) {
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        Map.Entry<String,JsonElement> table = jsonObject.entrySet().iterator().next();
        String tableName = table.getKey();
        JsonElement rows = table.getValue();
        try {
            Class<?> rowClass = Class.forName("[Lnewpackage." + tableName + ";"); // explanation see below this code snippet
            // rowClass is an array class!
            Object[] parsedRows = gson.fromJson(rows, rowClass);
            // do something with parsedRows
            for (Object x : parsedRows) {
                System.out.println(x);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Assuming a "table definition" consists of a property named as the class ob the objects in the table, with the objects as array value of that property.

Explanation of Class.forName("[Lnewpackage." + tableName + ";")

This retrieves the Class instance for the array type of a class located in the package newpackage, e.g. newpackage.TableA[] (note the []). Class.forName("A") returns the instance representing the class A. Class.forName("[LA;") returns the instance representing the "class" of an array of As. Using it as a parameter for fromJson(...) it results in the parsing of a JSON array of A-objects.

Upvotes: 1

hurricane
hurricane

Reputation: 6724

First of all you have to decide what is your base json structure ? Max identifiers, max values, max objects,max arrays...

  1. Create your full json structure with texteditor or http://www.jsoneditoronline.org/ or http://jsonlint.com/ etc.

Let's think this is my full json structure:

{
  "array": [
    1,
    2,
    3
  ],
  "boolean": true,
  "null": null,
  "number": 123,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  },
  "string": "Hello World"
}
  1. Create your Java Classes as like as your json identifiers. You can use http://json2csharp.com/ convert to Java.

And these are my Java Classes:

public class Object
{
    public string a { get; set; }
    public string c { get; set; }
    public string e { get; set; }
}

public class RootObject
{
    public ArrayList<int> array { get; set; }
    public Boolean boolean { get; set; }
    public Object @null { get; set; }
    public int number { get; set; }
    public Object @object { get; set; }
    public string @string { get; set; }
}
  1. Create your DAO for convert these to structure to them.

For Java;

String data = "jsonString"; 
RootObject root = new GsonBuilder().create().fromJson(data, RootObject.class);

For Json;

Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy").create();
String json = gson.toJson(obj);

Upvotes: 1

Related Questions