4

I have a question about toJson function in google.Gson library.

I read online here that I can use it like this toJson(_) what does the underscore sign mean? In the documentation the parameter represents the target type, can you please explain more about what should I pass if I just want to convert log data to Json?

Here's the code I'm asking about:

  private var gson = new Gson()
 val tweetStream = TwitterUtils.createStream(ssc, Utils.getAuth)
      .map(gson.toJson(_))
Lisa
  • 3,121
  • 15
  • 53
  • 85

1 Answers1

-1

Gson has desined to make all the Json mess extremely easy.

Anyway, I have used Gson in java on android and it's look like this:

static public <T extends JsonAble> T getJson(Context context, Class<T> jsonClass){
    String strClassName = jsonClass.getSimpleName();
    String strJson = getTextFromFile(context, strClassName);
    T objReturn = gsnEncoder.fromJson(strJson, jsonClass);
    return objReturn;
}

As you can see, you only need to spesific the object and Gson will do the magic.

EDIT: I have posted fromJson instead toJson), the idea is same, give me a second to fix it.

static public <T extends JsonAble> boolean setObject(Context context, T Obj)  {
    boolean IsSucceed = false;
    String strClassName = Obj.getClass().getSimpleName();

    try {
        String strObj =  DL.gsnEncoder.toJson(Obj);
        IsSucceed = DL.setTextToFile(context, strClassName, strObj);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return IsSucceed;
}
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
Remy
  • 1,053
  • 1
  • 19
  • 25
  • 1
    This explains how to use getJson()/toJson() in Java, but it doesn't explain the meaning of the _ character in scala. – M4N Jul 22 '15 at 11:59
  • @M4n Look at the comment on the question, the question about the underscore has already answered. I just explained how to use Json (The second question). – Remy Jul 23 '15 at 17:09