how to correctly pick the json structure - java

Hi i have a php script that input user data into mysql and from mysql i get the results in an array and finally to json format by json_encode functino of PHP. The contents of the file are provided below.
[{"priority":"1","rule_body":"person(?x),pid(?y),haspid(?x,?y)","cons":"patient(?x)","boolean":"1"},
{"priority":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)","boolean":"1"},
{"priority":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)","boolean":"1"},
{"priority":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)","boolean":"1"},
{"priority":"1","rule_body":"aaa(bbb)","cons":"z(x)","boolean":"1"},
{"priority":"1","rule_body":"aaa(bbb)","cons":"z(x)","boolean":"1"},
{"priority":"1","rule_body":"aaa(bbb)","cons":"z(x)","boolean":"1"}]
However now i need to get the json read in the JAVA and for ease i copy and paste the contents of the json file to string. I am able to read the contents but the positions has changed to the following sequence
here is the output
LENGTH IS____7
{"priority":"1","boolean":"1","rule_body":"person(?x),pid(?y),haspid(?x,?y)","cons":"patient(?x)"}
{"priority":"1","boolean":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)"}
{"priority":"1","boolean":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)"}
{"priority":"1","boolean":"1","rule_body":"patient(?x),hasbp(high)","cons":"situation(emergency)"}
{"priority":"1","boolean":"1","rule_body":"aaa(bbb)","cons":"z(x)"}
{"priority":"1","boolean":"1","rule_body":"aaa(bbb)","cons":"z(x)"}
{"priority":"1","boolean":"1","rule_body":"aaa(bbb)","cons":"z(x)"}
as you can see that the boolean has to be in the end but it pops up on the second number. i treid differenct codes from tutorials and did some my own as below but the result is same: help is needed in this matter.
jsonInput=[....as shown above the json contents....]
JSONArray ja = new JSONArray(jsonInput);
System.out.println("LENGTH IS____"+ja.length());
for(int x=0;x<ja.length();x++)
{
JSONObject jb = ja.getJSONObject(x);
System.out.println(jb);
}
System.out.println("KKKKKKKKKKKKKKKKKKKKKKKKKKKKKK");

JSON doesn't specify an order for keys As Adrian Smith said :
JSON libraries are free to rearrange the order of the elements as they see fit. This is not a bug.
You probably use org.json. You can use the getString("myKey") to access the value in your JSONObject without knowing his position.
An other solution is to create a class that represents your data:
public class myClass{
private int priority;
private String rule_body;
private String cons;
private String boolean; //STRING ! 1 is not a valid boolean value.
}
Then create an ArrayList of your class and deserialize your JSON in it with Gson.
Gson myGsonTool = new Gson();
ArrayList<myClass> myData = gson.fromJson(myJsonString, ArrayList<myClass>.class);
Then, you have a POJO with all your data. You can access easily to your data now:
//If i want the value of rule body:
myData.get(0).getRule_Body();
I do not know the purpose of your program, so this is maybe not the best solution.
Edit: Gson maintains the order of records.

Related

How to properly serialize and deserialize an array of objects into/from json?

I'm trying to implement a friends list which needs to be stored in a .json file, in Kotlin/Java with libgdx, but this isn't neccesary(Java is fine).
My code for (1) doesn't work so instead of pasteing it here I'll just try to explain my design and only paste the one for (2) as this I believe is closer to a good implementation.
I made a "Friend" class. When adding a new friend the main thread created such an object, then I read the existing "FriendsList.json" into a string, edited the string by removing "]" and appending the serialized Friend object and a "]" to close the array.
I had and still have a feeling this isn't good, so I changed it.
I made a "FriendArray" class, in which I thought of storing "Friend" objects in an List. I think this would allow me to get rid of the string manipulation code, and just serialize the FriendList class itself, which would hopefully also be easier to read. One of the problems is that addFriendToListOfFriends() doesn't add the data in the objects (it adds "{}" instead of also inserting the name and id).
What do you think of (2) ? Do you know a better way of doing this?
(Just to be clear, I'm more interested in the design and less about compilable code)
import com.badlogic.gdx.files.FileHandle
import com.unciv.json.json (this is com.badlogic.gdx.utils.Json)
import java.io.Serializable
class FriendList() {
private val friendsListFileName = "FriendsList.json"
private val friendsListFileHandle = FileHandle(friendsListFileName)
private var friendListString = ""
var arrayOfFriends = FriendArray()
fun getFriendsListAsString(): String {
return friendsListFileHandle.readString()
}
fun addNewFriend(friendName: String, playerID: String) {
val friend = Friend(friendName, playerID)
arrayOfFriends.addFriendToListOfFriends(friendName, playerID)
saveFriendsList()
}
fun saveFriendsList(){
friendListString = getFriendsListAsString()
friendListString = friendListString.plus(json().prettyPrint(arrayOfFriends))
friendsListFileHandle.writeString(friendListString, false)
}
}
class Friend(val name: String, val userId: String)
class FriendArray(): Serializable {
var nrOfFriends = 0
var listOfFriends = listOf<Friend>()
fun addFriendToListOfFriends(friendName: String, playerID: String) {
var friend = Friend(friendName, playerID)
listOfFriends.plus(friend)
}
}
You don't realy need a class FriendArray for this. You can just searialize a list to JSON. Also it's easier to load the existing friend list to a list, add the new friend to the list and serialize the new list, instead of appending a string.
This way you won't have to worry about the correct JSON format or string manipulation. You just add an object to a list, and serialize the list.
Something like this should work (in java, sorry I don't know enough kotlin to implement this):
public void addFriendAndSerializeToFile(Friend friend) {
// load existing friend list from the file
Json json = new Json();
// here the first parameter is the List (or Collection) type and the second parameter is the type of the objects that are stored in the list
List<Friend> friendList = json.fromJson(List.class, Friend.class, friendsListFileHandle);
// add the new friend to the deserialized list
friendList.add(friend);
// serialize the whole new list to the file
String serializedFriendListWithNewFriendAdded = json.prettyPrint(friendList);
// write to the file handle
fileHandle.writeString(serializedFriendListWithNewFriendAdded, false);
}

Is toString() mandatory while accessing the individual element of a JSON object in Java

I am quite new to Java and trying to understand the effect of using toString() while accessing the individual string elements of JSON object in Java.
Below are the steps followed:
Parse the JSON data. Let's assume only string elements are there in parsed JSON data.
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(json_data);
{
"firstname" : "new",
"lastname" : "human",
"id" : "some_id"
}
Try to access the individual elements.
Access without toString():
Public static String firstname = jsonObj.get("firstname");
Access with toString():
Public static String firstname = jsonObj.get("firstname").toString();
I do not see a difference when I try to print the data.
However I would like to know the difference between the above 2 methods, and also will there be any issues if I use without toString() in this particular case.
Appreciate your help.
Thank you
When you have some Int or other type of data type variables in your model class and you want to parse it into a string so for that we use toString(), it will convert int or any other data variable into a string, in your case here you already have string so no need to change again and again and JSON uses string variables when it comes from backend so that the purpose.
toString() returns string representation of property/object on which this method is called.
Whenever we print an object reference, it invokes the toString() method internally as a result , it is not making difference.
Because you are using Json, there is no difference.
You can use the Option, you like more

Find the occurrences of a key in JSON object in Java

I want to find a key in JSON that has repeated more than certain times or not. Based on the result I have to add some other key/value pairs to another JSON object. Is there any way that I can achieve this?
Thanks in Advance.
You can use the JSON Simple library to parse a json object: https://code.google.com/p/json-simple/
After that you can simply iterate over the objects and count their occurrences.
Maybe ... something like this:
public int countOccurrenceOfKey(final String jsonString, final String key) {
int occurrenceCounter = 0;
String[] jsonParts = jsonString.split(","); // maybe another splitter if comma appears within values
for(int i = 0; i < jsonParts.length; i=i+2) { // step to every second index so you only check the keys. start with i = 1 to check only values
String part = jsonParts[i];
if(part.contains(key) {
occurrenceCounter++;
}
}
return occurrenceCounter;
}
Why using a JSON library could probably create problems...
If your JSON string contains the same key more than 1 time (maybe you generated it manually):
A. The JSON converter could raise an exception and abort creating the object.
B. The library could only take the first or last appearance of the key so all other values for the same key could be lost.
Depends on the library implementation and on the JSON specification.
{
"responseCode": 200,
"responseMessage": "COMPLETE",
"responseData": "95W_RTXszAuuwsLxp8pA56UJQhMfNSVRQ-6OWd_f5-4tvBHp9WI4UgPBfop2AWPBY7xCI0QQcb2QwKuCRhSNdzbGOHlNL_Oectcb4xeUV_-cN8mqPo5iVyqXn_QtOtpn9GxlocFyLmXsjOKQgd5W_HsrmIwwldEwKLlcAzDTy9MIVSiZ3O97YXAzVZleV_yM0V4IqEd68wK3xGamCf05d_e4W-pnc56y3MSXRpu9op3Km0IdQAXj6gqeYCXe-AoZhj_OSP4pHpRJipixFpQGxWsSK2fhvZmdoNGxQRKtZGBzgJ9blCRFmNteio9_GbhOMXL6ySnSRbtSZ_RfBsjMu2m1MKWb0YOwQyOrIjKpQ3KOnXNCc0j54nF24YRmdFMZXbPktzrU90Y3HpzuX1xAZM0oAoUOm2xiJii1CJmH9YCOq3vR_eFneBFXFrOVCz29YKOkE4hlRHLlYxwgmWh91BFney0QIF9f9lyjHLTN958murr8dm6cS4BHSqWzeCrS86QuU4j7Zpgz6_jZUP-jK9Damjph2ZYJsIw5YHG_1dXRqse1RwbPYzP5xjADqgDVZm4IJfOwSiaYsuXtmm0hBj9fCj4DTVjVptnoYcv8Z649TquOYgbs-58st_bycROo9i1erwLz_nDdjIlQKPfz64a5UA",
"responseVersion": 3
}

How to check json for key and if it exists then set the value in java model Object

I have a model object which is initialized with default values. To refresh the content of object I call an web service and get the response and get the content from json object.
I want to check If json response contains the object or not. If it does then call the setter and set the data and if it doesn't then leave then don't set it. I have approx 300 fields in my object. How I can do it with less code. I am listing my current approach.
My Model object is like
public class MyObject {
private String str1 = "Initial Value1";
private String str2 = "Initial Value2";
public void setStr1(String str1)
{
this.str1 = str1;
}
public void setStr2(String str2)
{
this.str2 = str2;
}
public String getStr1(){
return str1;
}
public String getStr2(){
return str2;
}
}
my json response be like
{
"val_one":"New Value1",
"val_two":"New_value2"
}
Now at run time I need to set the value from json response
MyObject myObject = new MyObject();
if(jsonObject.has("val_one"));
myObject.setStr1(jsonObject.get("val_one"));
if(jsonObject.has("val_two"));
myObject.setStr2(jsonObject.get("val_two"));
Now how to do it in a better and efficient
If both sides are using JAVA then why not just use json-io. You can create an object as normal. ie
Animal a = new Aminmal() andimal.setName("bob");
Then use json-io to make it into json -- stream to where ever it needs to be... use json io to change back to object
This can be done using
JsonWriter.objectToJson(Object o);
JsonReader.jsonToJava(String json);
https://code.google.com/p/json-io/
json-io is also extremely light weight and quicker than most if not all other third party json library's that I have used.
That being said if you want to have more control on the output ie.. date conversions etc.. then look at GSON.
https://code.google.com/p/google-gson/
Another option, in addition to the other suggestions is gson. Here the link for gson information.
Essentially the idea with gson being that you define an object to represent the JSON structure that you are receiving. So somewhat like what you have now, you'd just need to change the object attributes to match the names of the JSON fields, ie 'val_one' and 'val_two'.
Then you just need to use gson to create the object from the JSON text, eg:
Gson gson = new GsonBuilder().create();
MyObject json = gson.fromJson(jsonStr, MyObject.class);
Why do you want to take of the object model mapping yourself? If you take spring then you can use the jackson mapper and have it all done for you.
If you don't want to use spring then you still can use jackson2 and let it handle the parsing:
http://wiki.fasterxml.com/JacksonRelease20

Convert JSONObject which contains \" to a normal string with JSON

I receive a string from an http request which contains data such as:
{"status":1,"Type":3,"Data":"<p style=\"padding-left:80px\"><\/p><ol><li><span style=\"color:#ff0000\">This<\/span><\/li><li>is a<\/li><li><strong>m<span style=\"background-color:#66cc00\">are<\/span><\/strong><\/li><\/ol><p><\/p><p style=\"padding-left:80px\"><strong style=\"text-align:left\"><span style=\"background-color:#66cc00\"><\/span><\/strong><\/p> "}
I convert it to a JSONObject like so:
jsonObj = new JSONObject(result);
I then need to get the html as a String to display in a TextView,
I have tried this:
String data = jsonObj.getString("data");
but data remains null. This works with simple json strings, but i think it might be cause of the " characters.
You are using "data" with a lowercase d, but your JSON contains "Data" with a capital D. Use this:
jsonObj.getString("Data");
You have used "data" instead of "Data". This is the only silly mistake you did. To avoid such type of typo mistake, always user final static String to access them from anywhere.
final static String KEY_DATA = "Data";
Then access it inside your class (suppose class name is Aclass):
jsonObj.getString(KEY_DATA);
And in other classes:
jsonObj.getString(Aclass.KEY_DATA);
This is a good practice indeed and no possibility of typo mistake!

Categories

Resources