1

I am attempting to recreate the below JSON in JAVA.

[{                  
"Operation": {
    Product: "MyProduct",
    Noun: "MyNoun",
    Verb: "MyVerb"
},
"Authentication": {
    UserID: "UserName",
    Password: "Password"
}}]

I feel like the Maps are the way to go. But I am having trouble forming the proper structure.

Map<String,String> opsDictionary =  new HashMap<String,String>();
    opsDictionary.put("Product","MyProduct");
    opsDictionary.put("Noun","MyNoun");
    opsDictionary.put("Verb", "MyVerb");

Map<String,String> authDictionary =  new HashMap<String,String>();
    authDictionary.put("UserID","UserName");
    authDictionary.put("Password", "Password");


JSONObject postdata = new JSONObject();
postdata.put("Operation", opsDictionary);
postdata.put("Authentication", authDictionary);

Which spits out this INCORRECT version:

{
    "Authentication": "{UserID=CADEMO, Password=TESTPASSORD}",
    "Operation": "{Noun=User, Product=TOPSInventory, Verb=Authenticate}"
}

I toyed with the idea of packaging up the Maps in a bundle

Bundle dataBundle = new Bundle();
dataBundle.putStringArray("Operation", opsDictionary);
dataBundle.putStringArray("Authentication", authDictionary);

What am I doing wrong?

I was able to replicate this format in my iOS version using Dictionaries.

 NSMutableDictionary * dicOperation = [[NSMutableDictionary alloc]init];
    [dicOperation setValue:product forKey:@"Product"];
    [dicOperation setValue:noun    forKey:@"Noun"];
    [dicOperation setValue:verb    forKey:@"Verb"];

    NSMutableDictionary * dicAuthentication = [[NSMutableDictionary alloc] init];
    [dicAuthentication setValue:username   forKey:@"UserID"];
    [dicAuthentication setValue:password forKey:@"Password"];


    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictPackage options:NSJSONWritingPrettyPrinted error:&error];

I was hoping there was a similar solution for Android.

user-44651
  • 3,924
  • 6
  • 41
  • 87
  • 3
    Why don't you use a 3rd party library like Jackson or GSON? – Shmuel Feb 16 '16 at 15:28
  • I want to use native tools/languages, once I learn how it is done then, I might want to use 3rd party tools. – user-44651 Feb 16 '16 at 15:29
  • 1
    check also your json...is not valid – appersiano Feb 16 '16 at 15:31
  • It may not be valid, but that is what I have to work with. – user-44651 Feb 16 '16 at 15:37
  • Its impossible to create an invalid json, except for writing a string yourself. You are missing a closing `}` before the final `]`... Aka, your braces do not match! The `[` `]` indicate an array of objects that contains an `Authentication` and `Operation` (with the missing bracket added) – IAmGroot Feb 16 '16 at 15:40
  • Take a look at http://stackoverflow.com/a/18983290/940834 for usages, which provide examples of everything you are trying to do – IAmGroot Feb 16 '16 at 15:42
  • how about offline json files and extracting it from java ? – erluxman Feb 16 '16 at 15:43
  • You would be better off creating actual objects (object oriented programming), where each object represents the entities you have (Operation, Authentication), and have properties within the objects. Then you have a 3rd objects that has instances of these two and is what you would serialize to json. – pczeus Feb 16 '16 at 15:44
  • The keys Product, Noun, Verb etc... can't be surrounded with quote marks. – user-44651 Feb 16 '16 at 15:45
  • See my updated question with the iOS implementation that works. – user-44651 Feb 16 '16 at 15:52
  • @Firemarble SHame you wont follow the link, though i noticed you fixed the json in your question that i pointed out. Change `putStringArray` to `put` and then attach into an jsonarray, your entire object. – IAmGroot Feb 16 '16 at 15:54
  • @Doomsknight I did follow the link and I am looking at it now. I updated my question because it was bad copy and paste job from my text editor that I used to spell check.... – user-44651 Feb 16 '16 at 15:55
  • Good stuff. You should be able to produce your desire results from it :) – IAmGroot Feb 16 '16 at 15:56
  • @Doomsknight I don't see what you're talking about `putStringArray` isn't in the link you provided. – user-44651 Feb 16 '16 at 15:57
  • @Firemarble Sorry if its confused, dont use `HashMap` or `putStringArray` as attempted above in your code, use `JSONObject.put` as per the linked example. – IAmGroot Feb 16 '16 at 16:02
  • @Firemarble where did you copy-paste that Json? If you get it from a browser you should copy from the text version and not the preview... – alex Feb 16 '16 at 16:04
  • Ive posted an answer for clarification – IAmGroot Feb 16 '16 at 16:05
  • 1
    I believe that @Doomsknight answer below is the one you are looking for .. but just a suggestion to modify the json in the question to become valid (surround the Properties keys with double quotes, e.g. "Product") .. always validate your target json if you are building it .. many tools online like [jsonlint](http://jsonlint.com/) – M.R.M Feb 16 '16 at 16:16
  • correct JSON in this case would have been [{ "Operation": { "Product": "MyProduct", "Noun": "MyNoun", "Verb": "MyVerb" }, "Authentication": { "UserID": "UserName", "Password": "Password" } }] – The Roy Feb 16 '16 at 16:43

4 Answers4

3

You do not need to use Hashmap. That is probably what is causing the string concatenated results.

It should read this

JSONObject opsDictionary = new JSONObject();
    opsDictionary.put("Product","MyProduct");
    opsDictionary.put("Noun","MyNoun");
    opsDictionary.put("Verb", "MyVerb");


JSONObject authDictionary = new JSONObject(); 
    authDictionary.put("UserID","UserName");
    authDictionary.put("Password", "Password");


JSONObject postdata = new JSONObject();
postdata.put("Operation", opsDictionary);
postdata.put("Authentication", authDictionary);

And if you are intending to create an array, finally attach to an array (in a loop or as required):

JSONArray ja = new JSONArray();
ja.put(postdata );

Code usage from How to create correct JsonArray in Java using JSONObject

Community
  • 1
  • 1
IAmGroot
  • 13,760
  • 18
  • 84
  • 154
-1

I'm not sure for my answer. Since i use jsonobject, jsonarray and Gson library, I worked only with simple object (string, boolean, number etc...), custom objects defined by "{}" and array of custom object.

Inside an array all element (custom or not) have got the same structure. So che fields of the first element are the same of second one. In your case I see only an associative array, not a real array. I'm not sure Gson or json provide, or are useful for your data. Maybe you have to use a custom object calles X wheere inside there are 2 custom object called Y and Z, because Y and Z have got different structure.

But I repeat...maybe my idea is wrong.

user3528466
  • 186
  • 2
  • 17
-1

you can do that by creating the proper structure of the json using classes the serialize , deserialize as you need.

first class MyOperation

public class MyOperation{
    private String Product = "";
    private String Noun = "";
    private String Verb = "";

    //setters and getters
}

second class MyAuthentication

public class MyAuthentication{
    private String UserID = "";
    private String Password = "";

    //setters and getters
}

and the -holder- class MyContent

public class MyContent{
    private MyOperation Operation = new MyOperation();
    private MyAuthentication Authentication = new MyAuthentication();

    //setters and getters
}

your JSON is an array of type MyContent you can serialize, deserialize using Gson:

//serialize example
MyContent myContent[] = new MyContent[1];
myContent[0] = new MyContent();
myContent[0].setMyOperation(....);
myContent[0].setMyAuthentication(....);

Gson gson = new Gson();
String jsonString = gson.toJson(myContent, MyContent[].class);
Yazan
  • 6,074
  • 1
  • 19
  • 33
-2

The JSON you report is not valid. It doesn't matter what you have, if you want to work with JSON you have to follow JSON rules. If you have doubt about the format, you can check it here

Some working format could be something like this

{
     "Operation": [
    {
      "Product": "MyProduct",
      "Noun": "MyNoun",
      "Verb": "MyVerb"
    }
  ],
       "Authentication": [
      {
      "UserID": "UserName",
      "Password": "Password"
    }
  ]
}

In general, JSON can be thought as a Tree. Every node of the tree can be:

  • an item

    {
    "item1Name": "item1Value",
    "item2Name": "item2Value",
    ...
    }
    
  • an array

    [
    "val1",
    "val2",
    ...
    ]
    
  • a subnode

    {
    "array": ["arrayitem1", ...],
    "itemX": "itemXValue",
    ...
    }
    

proper values can be numbers or strings, proper "keys" can be just strings.

In Java, you can easily map the items as Map<String, String> and arrays as List<Map<String,String>>

EDIT: once you get the right classes in the structure, you have to use the proper serializer. Otherwise toString() will be called and the wrong result (as you showed) will come out

alex
  • 115
  • 6