We have to parse a json structure similar to below.
project {
header {
}
pool {
}
cmp {
name = "";
id = "";
desc = "";
cmp [
{
name = "";
id = "";
desc = "";
}
{
name = "";
id = "";
desc = "";
}
{
name = "";
id = "";
desc = "";
cmp [
{
name = "";
id = "";
desc = "";
}
}
}
}
The issue is, cmp element is present in the json infinitly (and it is recursive too).
The cmp element contains lots of properties other than name, id and desc. But we need only name, id and desc to extract from the jSON.
I can able to parse the JSON string using com.json.parsers.JSONParser. But populating the parsed JSON to a model class/bean class is not working. It may be a simple logic. But I cannot. Please help...
The json file is generated as an output of one modeling software.
I want to parse this, using java. Can somebody help me to parse this?
Hope I have explained the issue correctly. Your help will be helpful for us.
You can do this with Jackson, just create your object with all the fields that may or may not be present in the message. All the fields not present in the message will end up as null (or default value for primitives) in the resulting object.
Just have the object contain a copy of itself and that will handle the recursion
#XmlRootElement
public class Foo {
Foo recursiveFoo; // will be null or another instance of Foo
int intData; // Will be 0 or an integer value
String strData; // Will be null or a String value
// Getters and setters here
}
Take a look at Google Gson library. With it you can do things like:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
//(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
//==> json is {"value1":1,"value2":"abc"}
//(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
//==> obj2 is just like obj
Related
JSON values that I get from server:
{
"Status":0,
"Message":"",
"Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"}
}
Getting the result as 'response' after connection and I am able to show my JSON string results on the screen.
JSONObject json = new JSONObject(response);
String status = json.getString("Status");
String message = json.getString("Message");
String result = json.getString("Result");
responseView.setText("Status" + status+ "Message" + message" + Result" + result);
I am okay the results of "Status" and "Message" but not with "Result" because want to separate "Result" objects as and able use each of them as objects.
For example:
When I type OB in my app, I will get the result S.C. Blue Air
Instead of :
String result = json.getString("Result");
use
if(json.get("Result") instanceof JSONObject){
JSONObject object = (JSONObject) json.get("Result");
//do what you want with JSONObject
String ob = object.get("0B");
}
If you want to store it some way you can put it to Map or create object if always it is same data
You can use some libraries such as Gson (Google) or Moshi (Square)
Those libraries allows you to declare your model as a plain java class (commonly called POJOS) annotated in some way that this libraries bind your properties in the JSON to your java properties.
In your case:
JSON:
{
"Status":0,
"Message":"",
"Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"}
}
MODEL:
public class MyCallResponse {
#SerializedName("Status")
int status;
#SerializedName("Message")
String message;
#SerializedName("Result")
Result result;
}
public class Result {
#SerializedName("0B")
String b;
#SerializedName("0Y")
String y;
#SerializedName("0X")
String x;
}
In this case, with Gson you can do:
MyCallResponse response = new Gson().fromJson(json, MyCallResponse.class);
Log.i("Response b", response.result.b);
Look at the documentation for more information about both libraries.
try this :
JSONObject json = new JSONObject(response);
JSONObject resultObj = json.getJSONObject("Result");
String OB = resultObj.getString("OB");
Try this
String base = ""; //Your json string;
JSONObject json = new JSONObject(base);
JSONOBject resultJson = json.getJSONObject("Result");
// Get all json keys "OB", "OY", "1X" etc in Result, so that we can get values against each key.
Set<Map.Entry<String, JsonElement>> entrySet = resultJson.entrySet();
Iterator iterator = entrySet.iterator();
for (int j = 0; j < entrySet.size(); j++) {
String key = null; //key = "OB", "OY", "1X" etc
try {
Map.Entry entry = (Map.Entry) iterator.next ();
key = entry.getKey ().toString ();
//key = "OB", "OY", "1X" etc
}
catch (NoSuchElementException e) {
e.printStackTrace ();
}
if (!TextUtils.isEmpty (key)) {
Log.d ("JSON_KEY", key);
String value = resultJson.getString(key);
//for key = "0B", value = "S.C. Blue Air"
//for key = "0Y", value = "FlyYeti"
//for key = "1X", value = "Branson Air"
}
}
It works with any array with dynamic json key.
Don't forget to accept the answer & upvote if it works.
Is it possible to change the name of a Json property without serialization with Gson? For example, given this Json
{
"1": {
...
},
"2": {
...
}
}
could I change the "1" to a "3" without removing its contents. I know that the addProperty method adds a new property, or overwrites an existing property with a new value, but I want to change the name of a property without affecting its value. Also, pasting the existing value as the second argument of addProperty will not suffice.
EDIT: To add more context, I will explain the bigger picture. I have a JSON string that is a couple thousand lines long. I'm writing a program leveraging Gson in order to change the values in that JSON string. I am at a point where I not only want to change the values of properties, but the names of the properties themselves. I have done everything so far without serialization.
Here is a snippet of the Java I wrote:
String file = "\\temp.json";
FileReader reader = new FileReader(file);
JsonStreamParser parser = new JsonStreamParser(reader);
// Parse entire JSON
JsonElement element = parser.next();
// Get root element
JsonObject sites = element.getAsJsonObject();
// Get first child element
JsonObject site1 = sites.getAsJsonObject("1");
JsonObject clust1 = site1.getAsJsonObject("CLUST");
for(int i = 1; i < 12; i++) {
// "Dynamic" variable
String num = Integer.toString(i);
// Get property whose name is a number, has siblings
JsonObject one = custCluster1.getAsJsonObject(num);
one.getAsJsonObject().addProperty("name", "cluster" + i);
JsonObject subOne = one.getAsJsonObject("SUB");
subOne.getAsJsonObject().addProperty("name", "aName" + i);
for(int n = 1; n < 1002; n++) {
// "Dynamic" variable
String inst = Integer.toString(n);
// Get property whose name is a number, has siblings
JsonObject subSub = subOne.getAsJsonObject(inst);
// If the property doesn't exist, then don't execute
if(subSub != null) {
JsonArray subSubArray = subSub.getAsJsonArray("SUBSUB");
subSub.getAsJsonObject().remove("name");
int m = 0;
while(m < subSubArray.size()) {
subSubArray.get(m).getAsJsonObject().remove("SR");
subSubArray.get(m).getAsJsonObject().remove("FI");
subSubArray.get(m).getAsJsonObject().remove("IND");
subSubArray.get(m).getAsJsonObject().addProperty("ST", "1");
subSubArray.get(m).getAsJsonObject().addProperty("ID", "2");
subSubArray.get(m).getAsJsonObject().addProperty("DESCR", "hi");
m++;
}
m = 0;
}
}
}
Thanks to #mmcrae for helping and suggesting this method.
Since I'm already saving the (key, value) pairs in variables, you can remove the property whose name you want to change from the parent, and then add it back with a new name and the content that was already saved.
Like this:
JsonObject sites = element.getAsJsonObject();
JsonObject site1 = sites.getAsJsonObject("1");
JsonObject clust1 = site1.getAsJsonObject("CLUST");
site1.remove("CLUST");
site1.add("NEWCLUST", clust1);
i have here a little project that getting data from a table and return it as json with the use of json, but the json its returning seems to be a string. it has back slash, can someone knows what it causes.
Result result = new Result();
result.responseCode = "00";
result.responseMessage = "Successful";
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.serializeNulls().create();
String x = "x";
String name="",address ="",msisdn="",email="";
Details details = new Details();
for(DataRow dr : drw_){
name = dr.get("NAME").toString();
details.name = name;
address = dr.get("ADDRESS").toString();
details.address = address;
msisdn = dr.get("CONTACTNUMBER").toString();
details.msisdn = msisdn;
email = dr.get("EMAIL").toString();
details.email = email;
gson.toJson(details);
result.detailsList.add(gson.toJson(details));
}
System.out.println(gson.toJson(details));
System.out.println(gson.toJson(result));
Sample output:
{"responseMessage":"Successful",
"responseCode":"00",
"detailsList":["{\"name\":\"name1\",
\"address\":\"address st 1\",
\"msisdn\":\"09211231234\",
\"email\":\"email#someweb.com\"}"
,"{
\"name\":\"testname\",
\"address\":\"testadress st 1 CITY\",
\"msisdn\":\"+639171234567\",
\"email\":\"myemail#someweb.com\"}
"]
}
Expected Output:
{"responseMessage":"Successful",
"responseCode":"00",
"detailsList":[{"name":"name1",
"address":"address st 1",
"msisdn":"09211231234",
"email":"email#someweb.com"}
,{
"name":"testname",
"address":"testadress st 1 CITY",
"msisdn":"+639171234567",
"email":"myemail#someweb.com"}
]}
The Slashes are escape because of the " value. This can break a string. For example
String x = "{"name":"name1"}" // Not a valid string
String x = "{\"name\":\"name1\"}" // Valid string
Try it out and the compiler will show you the errors.
You are converting it to gson twice.. So the second parsing escapes the double quotes. Try like this
Result result = new Result();
result.responseCode = "00";
result.responseMessage = "Successful";
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.serializeNulls().create();
String x = "x";
String name="",address ="",msisdn="",email="";
Details details = new Details();
for(DataRow dr : drw_){
name = dr.get("NAME").toString();
details.name = name;
address = dr.get("ADDRESS").toString();
details.address = address;
msisdn = dr.get("CONTACTNUMBER").toString();
details.msisdn = msisdn;
email = dr.get("EMAIL").toString();
details.email = email;
result.detailsList.add(details);
}
System.out.println(gson.toJson(details));
System.out.println(gson.toJson(result));
Did you try: result.detailsList.add(details);? You should let JSON serialize everything in one go and not put a JSON String inside another object.
You are building a json where each element of detailList list field is an string containing the string representation of other Json previously generated:
result.detailsList.add(gson.toJson(details));
Your detailsList seems to be a list of strings.
detailsList should be a collection of a class Details objects instead of Strings.
This way, the line above should be changed to:
result.detailsList.add(details);
Otherwise, which is happening to you now, you are encoding strings containing quotes thus, these quotes are being encoding with escape characters.
The format of my json object is:
String jsonObjRecv = {
"response":{
"respobj":{
"id":<int>,
"number":<string>,
"validated":<boolean>
}
},
"status":"ok",
"errors":null
}
It works when code is:
JSONObject jsonObjCont = new JSONObject(jsonObjRecv);
String getString= jsonObjCont.toString(2);
In this case getString != null and I can receive data, but when I try to get nested data of JSON object as like:
JSONObject jsonObjCont = new JSONObject(jsonObjRecv);
JSONObject regNumber = jsonObjCont.getJSONObject("respobj");
String number= regNumber.getString("number");
it dont work.
I tried to use GSON library, but it works when:
public String parse(String jsonObjRecv) {
JsonElement jelement = new JsonParser().parse(jsonObjRecv);
String result = jelement.toString();
return result;
and don't work :
public String parse(String jsonObjRecv) {
JsonElement jelement = new JsonParser().parse(jsonObjRecv);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("respobj");
String result = jobject.get("number").toString();
return result;
Where is my mistake?
The problem is you're not accessing your JSON object correctly - it's an object that contains a response object which contains a respobj object.
Gson example follows. Note the comment in the code - you need to get the response object then get the respobj from it.
public static void main( String[] args )
{
String jsonObjRecv = "{\"response\":{\"respobj\":{\"id\":1,\"number\":\"22\",\"validated\":true}},\"status\":\"ok\",\"errors\":null}";
JsonElement jelement = new JsonParser().parse(jsonObjRecv);
JsonObject jobject = jelement.getAsJsonObject();
// Here is where you're making an error. You need to get the outer
// 'response' object first, then get 'respobj' from that.
jobject = jobject.getAsJsonObject("response").getAsJsonObject("respobj");
String result = jobject.get("number").getAsString();
System.out.println(result);
}
Output:
22
Edit to add: Note I used getAsString() vs. toString() - if you use the latter you get the raw JSON which will incluse the quotes around the value (e.g. the output would be "22")
Can you recommend on a Json Deserializer that can deserialize into existing object (merge 2 objects)?
When the user submit a form I want to save that into the db this way:
this is the json from the client:
{"affiliateId":1,"name":"First Affiliate","email":"email#gmail.com","user.userName":"test","user.password":"pass-hashed","employee.employeeId":1}
Affiliate affiliateFromDb = affiliateApi.getFromDbById(1);
SomeDeserialization json = new SomeDeserialization();
affiliateFromDb = json.fromJson(affiliateFromJson , affiliateFromDb );//affiliateFromDb = target bean
Meaning that I want the affiliateFromJson to be interpolated into affiliateFromDb.
And than I will call
affiliateApi.save(affiliateFromDb);
Note that the json contains deep deserialize, user.userName
Thanks
Use Gson! In particular, see the Object Examples.
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
The only catch here — but you will have this same problem with any other JSON (de)serializer — is the nonstandard "deep" object format you want to work with. You would have to use something like this instead:
{"affiliateId":1,"name":"First Affiliate","email":"email#gmail.com","user": {"userName":"test","password":"pass-hashed"},"employee.employeeId":1}
http://www.json.org/javadoc/org/json/JSONObject.html
JSONObject jsonResponse = new JSONObject(responseString);