My Json structure is like
main = {
"hideIds1":["id1","id2","id3","id4"],
"hideIds2":["id11","id12","id13","id14"],
"maindHides1":["hideIds1","id7","id9"]
"maindHides2":["hideIds1","hideIds2","id14","id18"]
}
Looks "mainHides1" is extends all the values of "hideIds1".When i iterate "mainHides1" i have to check the key is having the values or not in the main JsonObject.In this iteration, first value becomes true but for other ids it wont need.
What i am expect here is when i access the "maindHides1" values it becomes like ["id1","id2","id3","id4","id7","id9"]. Will json do it automatically something like extends or i have to do it manually in program?
Or anyother samrtway to handle this problem.
You can use GSON library and caste your JSON into java object.Once you have java object with you you can do your required task.
For the option of manual, you can create your own hashset with keys from JSON and what you can do is that while adding values you can cross check if they are equal to any current key values. if yes then you can add its values in internal loop to the value set.
In JSON itself it is not possible but I suggest using something like TypeScript and just create your models as you want, It will be something like that:
interface IMainModel {
IDs: array;
}
var donut: IHides1Model = {
main: IMainModel,
IDs: array
};
JSON is pure type construction it is not a class,library or framework.
You would need to make this extension manually.
Related
I have a JSON string that I am using within a Scala programme by converting it into a ListMap to perform some tests, and then returning the results in an output JSON, along with the original JSON as a value. I cannot use a schema as the JSONs are changeable. The original JSON string is for example:
val originalJSONString =
{
"outerKey1": "",
"outerKey2": "",
"outerKey3": {
"innerKey1": "",
"innerKey2": "",
"innerKey3": ""
}
}
When I convert it to a ListMap using the below code, it will preserve the order of the outer keys, but not the inner keys as Object doesn't preserve the order.
val jsonListMap = mapper.readValue[ListMap[String, Object]](originalJSONString)
If I create a JSON that just contains the "outerKey3" key and its values, and the following code, it will preserve the order, but naturally will not work on the whole of the originalJSONString. The JSONs will always only have nesting of two levels.
val jsonListMap = mapper.readValue[ListMap[String, ListMap[String, String]]](originalJSONString)
There must surely be some way within this code to convert the keys with string values to Object/String and the keys with Map/ListMap values (i.e. outerKey3) to a ListMap? I want it to infer which data type it should be creating.
I was thinking about creating a function, or using Either/Option but I'm not sure these are appropriate.
(I am aware that JSON is by definition unordered and Scala/Java do not preserve order for this reason. Unfortunately without being able to convert the necessary values to ListMap the final JSON is unordered and the humans who will be reading it - not querying it - want it in order. I do not want to return the original string as the formatting would make my querying of the output JSON a nightmare. Also I would like to know if inferring data type in this way is possible for many other data wrangling issues outside of preserving JSON key order!)
Thank you in advance!
I know that this topic has been talked about, and the use of a LinkedHashMap is a 'hacky' way to maneuver this, but if I'm given thousands of JSON strings as input, and eventually want to output them back in their original form, is there anyway to preserve the order without manually constructing LinkedHashMaps.
For example a string like this
{"key":1,"surname":"Reed","given":"Ryan","address":{"state":"CA","postal":"90210"},"gender":"M"}
Right now if I parse the object like so:
JSONObject jsonObject = (JSONObject) parser.parse(str);
System.out.println(jsonObject);
My output will look like this:
{"surname":"Reed","gender":M,"address":{"postalCode":"90210","state":"CA"},"key":1,"given":"Ryan"}
Is there anyway I can get the output to match exactly like the given input?
In Json property structure, order does not matter. but if you have specific order in your mind you can use Jackson to order them in you desirable way, both in your server and client apps.
https://www.baeldung.com/jackson
http://www.davismol.net/2016/10/24/jackson-json-using-jsonpropertyorder-annotation-to-define-properties-serialization-order/
I think it is impossible by default.
You can refer to this RFC https://www.ietf.org/rfc/rfc4627.txt
An array is an ordered sequence of zero or more values.
If you want to hack it you can override the data structure and use the data structure which preserves the order.
I've got loads of the following to implement.
validateParameter(field_name, field_type, field_validationMessage, visibleBoolean);
Instead of having 50-60 of these in a row, is there some form of nested hashmap/4d array I can use to build it up and loop through them?
Whats the best approach for doing something like that?
Thanks!
EDIT: Was 4 items.
What you could do is create a new Class that holds three values. (The type, the boolean, and name, or the fourth value (you didn't list it)). Then, when creating the HashMap, all you have to do is call the method to get your three values. It may seem like more work, but all you would have to do is create a simple loop to go through all of the values you need. Since I don't know exactly what it is that you're trying to do, all I can do is provide an example of what I'm trying to do. Hope it applies to your problem.
Anyways, creating the Class to hold the three(or four) values you need.
For example,
Class Fields{
String field_name;
Integer field_type;
Boolean validationMessageVisible;
Fields(String name, Integer type, Boolean mv) {
// this.field_name = name;
this.field_type = type;
this.validationMessageVisible = mv;
}
Then put them in a HashMap somewhat like this:
HashMap map = new HashMap<String, Triple>();
map.put(LOCAL STRING FOR NAME OF FIELD, new Field(new Integer(YOUR INTEGER),new Boolean(YOUR BOOLEAN)));
NOTE: This is only going to work as long as these three or four values can all be stored together. For example if you need all of the values to be stored separately for whatever reason it may be, then this won't work. Only if they can be grouped together without it affecting the function of the program, that this will work.
This was a quick brainstorm. Not sure if it will work, but think along these lines and I believe it should work out for you.
You may have to make a few edits, but this should get you in the right direction
P.S. Sorry for it being so wordy, just tried to get as many details out as possible.
The other answer is close but you don't need a key in this case.
Just define a class to contain your three fields. Create a List or array of that class. Loop over the list or array calling the method for each combination.
The approach I'd use is to create a POJO (or some POJOs) to store the values as attributes and validate attribute by attribute.
Since many times you're going to have the same validation per attribute type (e.g. dates and numbers can be validated by range, strings can be validated to ensure they´re not null or empty, etc), you could just iterate on these attributes using reflection (or even better, using annotations).
If you need to validate on the POJO level, you can still reuse these attribute-level validators via composition, while you add more specific validations are you´re going up in the abstraction level (going up means basic attributes -> pojos -> pojos that contain other pojos -> etc).
Passing several basic types as parameters of the same method is not good because the parameters themselves don't tell much and you can easily exchange two parameters of the same type by accident in the method call.
I have some domain classes and i want to init and fill those classes with sample hardcode data , is there any method which i can fill data with any framework ?
For Example : List<Customer> should be filled with some mock data
Consider maintaining your test data in a JSON structure, and use a framework (e.g. google-gson) to deserialize the data into value objects.
If you wish to auto-generate random data, you might want to look into something like Quickcheck, which seems to be Java's equivalent of the .NET framework Autofixture.
As #ipavlic wrote, you might make your constructor generate some random data when the object is created.
You may store the data in a DB or a simple text file and read it from there when you fill your list.
You may combine aproach 1 and 2 and store possible field values in a file or somewhere else and fill the Object fields with these randomly chosen predefined values.
If you want fill list of Customer, there is this method Collections.fill(java.util.List, T) to fill list. This method replace current objects in list. If list is empty it won't fill.
You can put your hard-coded data in a constructor.
If it's mocking frameworks that you are after (as you indicate in comments), then take a look at e.g. Mockito.
I've a problem with storing a Json object as a java object, I'm not sure what structure to use to store something like this:
'tags':[{'CouchDB':1},{'JSON':1},{'database':1},{'NoSQL':1},{'document_database':1}]
I have tried 2 dimensional arrays, ArrayLists and Hashtables but didn't work, could be down to my poor implementation or I just have it wrong, need help with this ASAP please!
I'm using GSON to convert from the Json String to the Java object, and have other parts working fine, the problem is just having GSON parse this structure properly
Try using http://jsonlint.com/ to make sure that your JSON is valid (it doesn't seem to be)
If you change your tags to {"name":"couchdb"}, your Java class could look like this:
public class Tag
{
private String name;
...
}
And your container class could have a private List<Tag> tags;
Seems, like your tags are just a bunch of keys with a count (or something along those lines) attached to each one, i.e. key-value pairs which is just a hashtable e.g.:
{'tags':{'CouchDB':1,'JSON':1,'database':1,'NoSQL':1,'document_database':1}}
You should be able to convert the above without any trouble, if you can't I would say you have some sort of configuration issue as opposed to any kind of problem with the format of the data.