블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2738)
Unity3D (817)
Programming (475)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (58)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (53)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
05-03 19:49

[펌] Loop Dictionary

Programming/C# / 2016. 12. 7. 17:43
Code (CSharp):
  1. var enumerator = my_dictionary.GetEnumerator();
  2. while( enumerator.MoveNext() )
  3. {
  4.     // Access value with enumerator.Current.Value;
  5. }



[출처] https://forum.unity3d.com/threads/c-dictionary-loop.337804/

반응형
Posted by blueasa
, |

엑셀이 제공하는 편리한 기능 때문에 게임에 사용되는 데이터를 관리하기 위해서 엑셀을 많이 사용합니다.

하지만, 보안 문제나 이기종간 데이터 연동 문제 등이 있어서 엑셀 파일을 그대로 사용하는 경우 보다는 원하는 포맷으로 데이터를 변환해서 사용하는 경우가 더 많습니다.

게임  개발에서 사용하는 포맷은 csv, xml, binary 형태 등 여러가지고 있고, 저는 그 중에서 Json을 사용해 볼까하고 검색.

제일 먼저 검색된 툴은 node.js 로 제작된 xls-to-json

https://www.npmjs.com/package/xls-to-json

설치법과 사용법이 매우 간단해서 node가 설치되어 있다면, 아래 명령어로 간단하게 설치할 수 있습니다.

npm install xls-to-json

나머지는 사이트의 Usage 항목에 있는대로 하면 되는데,
막상 실행을 해서 변환된 json 파일을 보니 자료형에 대한 지원이 전혀 없이 모두 string 타입으로 변환.
Date 타입은 고사하고, int나 float로 지정된 값들도 모두 따옴표(“)가 양 옆에 붙어 버려서 LitJson과 같은 Json 변환 라이브러리에서 ToObject()를 실행할 수 없는 상태가 됩니다.

실제로 신나게 테스트를 했는데, 변환할 수 없다는 에러가 나와서 한동안 멍하니 있었습니다.

다시 검색을 해 보니, 국내 개발자인 최효진님께서 개발한 라이브러리가 있었습니다.

https://github.com/coolengineer/excel2json

이 툴이 좋은 점은 아래 스샷처럼, 데이터를 관리할 수 있고 결과물도 깔끔하게 나온다는 것. excel2json_shot

결과물은 아래처럼 나옵니다. 숫자에는 확실히 따옴표가 없어졌습니다.
Objects in Object, Object array 등을 지원해서 이걸 쓰기로 결정. LitJson에서도 잘 불러와 집니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
{
    "init": {
        "coins": 1000,
        "exp": 0,
        "golds": 0,
        "character": "wizard"
    },
    "buildings": {
        "barrack": {
            "color": "blue",
            "width": 200,
            "height": 200
        },
        "mine": {
            "color": "yellow",
            "width": 200,
            "height": 100
        },
        "gas": {
            "color": "red",
            "width": 100,
            "height": 100
        },
        "townhall": {
            "color": "black",
            "width": 200,
            "height": 200
        }
    },


[출처]

https://heartgamer.wordpress.com/2015/01/14/excel-%EB%8D%B0%EC%9D%B4%ED%84%B0%EB%A5%BC-json%EC%9C%BC%EB%A1%9C-%EB%B3%80%ED%99%98%ED%95%98%EA%B8%B0/

반응형

'Programming > JSON' 카테고리의 다른 글

[펌] Unity에서 Json 사용 시 고려할 라이브러리.  (0) 2016.08.08
[펌] SimpleJSON  (0) 2016.08.08
Convert Excel to JSON  (0) 2014.03.04
Posted by blueasa
, |

Restful API로 플랫폼간 연동을 하는 일들이 많다보니, Json 라이브러리는 필수라서 정보를 찾아 본 것을 정리.

우선 http://json.org/json-ko.html 에 정리되어 있는 C# 라이브러리를 먼저 보면

이 중에서 유니티 개발자 그룹 같은데서 많이 보이는 라이브러는 LitJson과 JsonFx..

* LitJson : http://lbv.github.io/litjson
이 라이브러를 추천하는 경우가 많은데, 다른 라이브러리들과 마찬가지로 iOS에서 serialize 문제가 있는 듯.

해결법 , http://forum.unity3d.com/threads/litjson-issue-on-ios.113181/ 참고.

* JsonFx : https://github.com/jsonfx/jsonfx
LitJson의 iOS 문제를 JsonFx를 사용해서 해결했다는 글이 보이길래 찾아봤는데,
Github에 올라온 패키지가 2년전 것. 물론 단순한 구조인 json 특성 상 딱히 건드릴만한 것이 없긴 하지만, 좀 써보고 판단을 해야 할듯.


[출처]

https://heartgamer.wordpress.com/2015/01/10/unity%EC%97%90%EC%84%9C-json-%EC%82%AC%EC%9A%A9-%EC%8B%9C-%EA%B3%A0%EB%A0%A4%ED%95%A0-%EB%9D%BC%EC%9D%B4%EB%B8%8C%EB%9F%AC%EB%A6%AC/

반응형

'Programming > JSON' 카테고리의 다른 글

[펌] Excel 데이터를 Json으로 변환하기  (0) 2016.08.08
[펌] SimpleJSON  (0) 2016.08.08
Convert Excel to JSON  (0) 2014.03.04
Posted by blueasa
, |

[펌] SimpleJSON

Programming/JSON / 2016. 8. 8. 10:21

SimpleJSON


Contents

 [hide

Description

SimpleJSON is an easy to use JSON parser and builder. It uses strong typed classes for the different JSONTypes. The parser / builder does not distinguish between different value types. Number, boolean and null will be treated like strings. This might cause problems when you need to build a JSON string that requires the actual types.

In short: The parser conforms to rfc4627, the generator does not.


I've updated (only) the source code embedded in the page, and it now appears to round-trip, although this isn't particularly well tested and it's a very naive implementation. Use .ToJSON(0) to use the round-trip version. -- Opless (talk) 22:39, 21 September 2014 (CEST)OPless

Usage

To use SimpleJSON in Unity you just have to copy the SimpleJSON.cs file into your projects "plugins" folder inside your assets folder.

If you want to use the compression feature when it comes to saving and loading you have to download the SharpZipLib assembly and place it next to the SimpleJSON.cs file. In addition you have to uncomment the define at the top of the SimpleJSON.cs file.

For language specific usage see below.

CSharp

Like most assemblies SimpleJSON is contained in its own namespace to avoid name collisions.

To use SimpleJSON in C# you have to add this line at the top of your script:

using SimpleJSON;

UnityScript (Unity's Javascript)

To use SimpleJSON in UnityScript you have to add this line at the top of your script:

import SimpleJSON;

For UnityScript it's vital to place the SimpleJSON.cs (and SharpZipLib if needed) into a higher compilation group than the UnityScript file that should use it. The usual place is the Plugins folder which should work in most cases.

Examples (C# / UnityScript)

This is the JSON string which will be used in this example:

{
    "version": "1.0",
    "data": {
        "sampleArray": [
            "string value",
            5,
            {
                "name": "sub object"
            }
        ]
    }
}


var N = JSON.Parse(the_JSON_string);
var versionString = N["version"].Value;        // versionString will be a string containing "1.0"
var versionNumber = N["version"].AsFloat;      // versionNumber will be a float containing 1.0
var name = N["data"]["sampleArray"][2]["name"];// name will be a string containing "sub object"
 
//C#
string val = N["data"]["sampleArray"][0];      // val contains "string value"
 
//UnityScript
var val : String = N["data"]["sampleArray"][0];// val contains "string value"
 
var i = N["data"]["sampleArray"][1].AsInt;     // i will be an integer containing 5
N["data"]["sampleArray"][1].AsInt = i+6;       // the second value in sampleArray will contain "11"
 
N["additional"]["second"]["name"] = "FooBar";  // this will create a new object named "additional" in this object create another
                                               //object "second" in this object add a string variable "name"
 
var mCount = N["countries"]["germany"]["moronCount"].AsInt; // this will return 0 and create all the required objects and
                                                            // initialize "moronCount" with 0.
 
if (N["wrong"] != null)                        // this won't execute the if-statement since "wrong" doesn't exist
{}
if (N["wrong"].AsInt == 0)                     // this will execute the if-statement and in addition add the "wrong" value.
{}
 
N["data"]["sampleArray"][-1] = "Test";         // this will add another string to the end of the array
N["data"]["sampleArray"][-1]["name"] = "FooBar"; // this will add another object to the end of the array which contains a string named "name"
 
N["data"] = "erased";                          // this will replace the object stored in data with the string "erased"


Download

Here's the whole thing packed as unityPackage and as seperate files including example / test scripts

Media:SimpleJSON.zip


SimpleJSON.cs

//#define USE_SharpZipLib
#if !UNITY_WEBPLAYER
#define USE_FileIO
#endif
/* * * * *
 * A simple JSON Parser / builder
 * ------------------------------
 * 
 * It mainly has been written as a simple JSON parser. It can build a JSON string
 * from the node-tree, or generate a node tree from any valid JSON string.
 * 
 * If you want to use compression when saving to file / stream / B64 you have to include
 * SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and
 * define "USE_SharpZipLib" at the top of the file
 * 
 * Written by Bunny83 
 * 2012-06-09
 * 
 * Modified by oPless, 2014-09-21 to round-trip properly
 *
 * Features / attributes:
 * - provides strongly typed node classes and lists / dictionaries
 * - provides easy access to class members / array items / data values
 * - the parser ignores data types. Each value is a string.
 * - only double quotes (") are used for quoting strings.
 * - values and names are not restricted to quoted strings. They simply add up and are trimmed.
 * - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData)
 * - provides "casting" properties to easily convert to / from those types:
 *   int / float / double / bool
 * - provides a common interface for each node so no explicit casting is required.
 * - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined
 * 
 * 
 * 2012-12-17 Update:
 * - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree
 *   Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator
 *   The class determines the required type by it's further use, creates the type and removes itself.
 * - Added binary serialization / deserialization.
 * - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ )
 *   The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top
 * - The serializer uses different types when it comes to store the values. Since my data values
 *   are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string.
 *   It's not the most efficient way but for a moderate amount of data it should work on all platforms.
 * 
 * * * * */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
 
 
namespace SimpleJSON
{
	public enum JSONBinaryTag
	{
		Array = 1,
		Class = 2,
		Value = 3,
		IntValue = 4,
		DoubleValue = 5,
		BoolValue = 6,
		FloatValue = 7,
	}
 
	public abstract class JSONNode
	{
		#region common interface
 
		public virtual void Add (string aKey, JSONNode aItem)
		{
		}
 
		public virtual JSONNode this [int aIndex]   { get { return null; } set { } }
 
		public virtual JSONNode this [string aKey]  { get { return null; } set { } }
 
		public virtual string Value                { get { return ""; } set { } }
 
		public virtual int Count                   { get { return 0; } }
 
		public virtual void Add (JSONNode aItem)
		{
			Add ("", aItem);
		}
 
		public virtual JSONNode Remove (string aKey)
		{
			return null;
		}
 
		public virtual JSONNode Remove (int aIndex)
		{
			return null;
		}
 
		public virtual JSONNode Remove (JSONNode aNode)
		{
			return aNode;
		}
 
		public virtual IEnumerable<JSONNode> Children
		{
			get {
				yield break;
			}
		}
 
		public IEnumerable<JSONNode> DeepChildren
		{
			get {
				foreach (var C in Children)
					foreach (var D in C.DeepChildren)
						yield return D;
			}
		}
 
		public override string ToString ()
		{
			return "JSONNode";
		}
 
		public virtual string ToString (string aPrefix)
		{
			return "JSONNode";
		}
 
		public abstract string ToJSON (int prefix);
 
		#endregion common interface
 
		#region typecasting properties
 
		public virtual JSONBinaryTag Tag { get; set; }
 
		public virtual int AsInt
		{
			get {
				int v = 0;
				if (int.TryParse (Value, out v))
					return v;
				return 0;
			}
			set {
				Value = value.ToString ();
				Tag = JSONBinaryTag.IntValue;
			}
		}
 
		public virtual float AsFloat
		{
			get {
				float v = 0.0f;
				if (float.TryParse (Value, out v))
					return v;
				return 0.0f;
			}
			set {
				Value = value.ToString ();
				Tag = JSONBinaryTag.FloatValue;
			}
		}
 
		public virtual double AsDouble
		{
			get {
				double v = 0.0;
				if (double.TryParse (Value, out v))
					return v;
				return 0.0;
			}
			set {
				Value = value.ToString ();
				Tag = JSONBinaryTag.DoubleValue;
 
			}
		}
 
		public virtual bool AsBool
		{
			get {
				bool v = false;
				if (bool.TryParse (Value, out v))
					return v;
				return !string.IsNullOrEmpty (Value);
			}
			set {
				Value = (value) ? "true" : "false";
				Tag = JSONBinaryTag.BoolValue;
 
			}
		}
 
		public virtual JSONArray AsArray
		{
			get {
				return this as JSONArray;
			}
		}
 
		public virtual JSONClass AsObject
		{
			get {
				return this as JSONClass;
			}
		}
 
 
		#endregion typecasting properties
 
		#region operators
 
		public static implicit operator JSONNode (string s)
		{
			return new JSONData (s);
		}
 
		public static implicit operator string (JSONNode d)
		{
			return (d == null) ? null : d.Value;
		}
 
		public static bool operator == (JSONNode a, object b)
		{
			if (b == null && a is JSONLazyCreator)
				return true;
			return System.Object.ReferenceEquals (a, b);
		}
 
		public static bool operator != (JSONNode a, object b)
		{
			return !(a == b);
		}
 
		public override bool Equals (object obj)
		{
			return System.Object.ReferenceEquals (this, obj);
		}
 
		public override int GetHashCode ()
		{
			return base.GetHashCode ();
		}
 
 
		#endregion operators
 
		internal static string Escape (string aText)
		{
			string result = "";
			foreach (char c in aText) {
				switch (c) {
					case '\\':
						result += "\\\\";
						break;
					case '\"':
						result += "\\\"";
						break;
					case '\n':
						result += "\\n";
						break;
					case '\r':
						result += "\\r";
						break;
					case '\t':
						result += "\\t";
						break;
					case '\b':
						result += "\\b";
						break;
					case '\f':
						result += "\\f";
						break;
					default   :
						result += c;
						break;
				}
			}
			return result;
		}
 
		static JSONData Numberize (string token)
		{
			bool flag = false;
			int integer = 0;
			double real = 0;
 
			if (int.TryParse (token, out integer)) {
				return new JSONData (integer);
			}
 
			if (double.TryParse (token, out real)) {
				return new JSONData (real);
			}
 
			if (bool.TryParse (token, out flag)) {
				return new JSONData (flag);
			}
 
			throw new NotImplementedException (token);
		}
 
		static void AddElement (JSONNode ctx, string token, string tokenName, bool tokenIsString)
		{
			if (tokenIsString) {
				if (ctx is JSONArray)
					ctx.Add (token);
				else
					ctx.Add (tokenName, token); // assume dictionary/object
			} else {
				JSONData number = Numberize (token);
				if (ctx is JSONArray)
					ctx.Add (number);
				else
					ctx.Add (tokenName, number);
 
			}
		}
 
		public static JSONNode Parse (string aJSON)
		{
			Stack<JSONNode> stack = new Stack<JSONNode> ();
			JSONNode ctx = null;
			int i = 0;
			string Token = "";
			string TokenName = "";
			bool QuoteMode = false;
			bool TokenIsString = false;
			while (i < aJSON.Length) {
				switch (aJSON [i]) {
					case '{':
						if (QuoteMode) {
							Token += aJSON [i];
							break;
						}
						stack.Push (new JSONClass ());
						if (ctx != null) {
							TokenName = TokenName.Trim ();
							if (ctx is JSONArray)
								ctx.Add (stack.Peek ());
							else if (TokenName != "")
								ctx.Add (TokenName, stack.Peek ());
						}
						TokenName = "";
						Token = "";
						ctx = stack.Peek ();
						break;
 
					case '[':
						if (QuoteMode) {
							Token += aJSON [i];
							break;
						}
 
						stack.Push (new JSONArray ());
						if (ctx != null) {
							TokenName = TokenName.Trim ();
 
							if (ctx is JSONArray)
								ctx.Add (stack.Peek ());
							else if (TokenName != "")
								ctx.Add (TokenName, stack.Peek ());
						}
						TokenName = "";
						Token = "";
						ctx = stack.Peek ();
						break;
 
					case '}':
					case ']':
						if (QuoteMode) {
							Token += aJSON [i];
							break;
						}
						if (stack.Count == 0)
							throw new Exception ("JSON Parse: Too many closing brackets");
 
						stack.Pop ();
						if (Token != "") {
							TokenName = TokenName.Trim ();
							/*
							if (ctx is JSONArray)
								ctx.Add (Token);
							else if (TokenName != "")
								ctx.Add (TokenName, Token);
								*/
							AddElement (ctx, Token, TokenName, TokenIsString);
							TokenIsString = false;
						}
						TokenName = "";
						Token = "";
						if (stack.Count > 0)
							ctx = stack.Peek ();
						break;
 
					case ':':
						if (QuoteMode) {
							Token += aJSON [i];
							break;
						}
						TokenName = Token;
						Token = "";
						TokenIsString = false;
						break;
 
					case '"':
						QuoteMode ^= true;
						TokenIsString = QuoteMode == true ? true : TokenIsString;
						break;
 
					case ',':
						if (QuoteMode) {
							Token += aJSON [i];
							break;
						}
						if (Token != "") {
							/*
							if (ctx is JSONArray) {
								ctx.Add (Token);
							} else if (TokenName != "") {
								ctx.Add (TokenName, Token);
							}
							*/
							AddElement (ctx, Token, TokenName, TokenIsString);
							TokenIsString = false;
 
						}
						TokenName = "";
						Token = "";
						TokenIsString = false;
						break;
 
					case '\r':
					case '\n':
						break;
 
					case ' ':
					case '\t':
						if (QuoteMode)
							Token += aJSON [i];
						break;
 
					case '\\':
						++i;
						if (QuoteMode) {
							char C = aJSON [i];
							switch (C) {
								case 't':
									Token += '\t';
									break;
								case 'r':
									Token += '\r';
									break;
								case 'n':
									Token += '\n';
									break;
								case 'b':
									Token += '\b';
									break;
								case 'f':
									Token += '\f';
									break;
								case 'u':
									{
										string s = aJSON.Substring (i + 1, 4);
										Token += (char)int.Parse (
											s,
											System.Globalization.NumberStyles.AllowHexSpecifier);
										i += 4;
										break;
									}
								default  :
									Token += C;
									break;
							}
						}
						break;
 
					default:
						Token += aJSON [i];
						break;
				}
				++i;
			}
			if (QuoteMode) {
				throw new Exception ("JSON Parse: Quotation marks seems to be messed up.");
			}
			return ctx;
		}
 
		public virtual void Serialize (System.IO.BinaryWriter aWriter)
		{
		}
 
		public void SaveToStream (System.IO.Stream aData)
		{
			var W = new System.IO.BinaryWriter (aData);
			Serialize (W);
		}
 
		#if USE_SharpZipLib
		public void SaveToCompressedStream(System.IO.Stream aData)
		{
			using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
			{
				gzipOut.IsStreamOwner = false;
				SaveToStream(gzipOut);
				gzipOut.Close();
			}
		}
 
		public void SaveToCompressedFile(string aFileName)
		{
 
#if USE_FileIO
			System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
			using(var F = System.IO.File.OpenWrite(aFileName))
			{
				SaveToCompressedStream(F);
			}
 
#else
			throw new Exception("Can't use File IO stuff in webplayer");
#endif
		}
		public string SaveToCompressedBase64()
		{
			using (var stream = new System.IO.MemoryStream())
			{
				SaveToCompressedStream(stream);
				stream.Position = 0;
				return System.Convert.ToBase64String(stream.ToArray());
			}
		}
 
#else
		public void SaveToCompressedStream (System.IO.Stream aData)
		{
			throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
		}
 
		public void SaveToCompressedFile (string aFileName)
		{
			throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
		}
 
		public string SaveToCompressedBase64 ()
		{
			throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
		}
		#endif
 
		public void SaveToFile (string aFileName)
		{
#if USE_FileIO
			System.IO.Directory.CreateDirectory ((new System.IO.FileInfo (aFileName)).Directory.FullName);
			using (var F = System.IO.File.OpenWrite (aFileName)) {
				SaveToStream (F);
			}
			#else
			throw new Exception ("Can't use File IO stuff in webplayer");
			#endif
		}
 
		public string SaveToBase64 ()
		{
			using (var stream = new System.IO.MemoryStream ()) {
				SaveToStream (stream);
				stream.Position = 0;
				return System.Convert.ToBase64String (stream.ToArray ());
			}
		}
 
		public static JSONNode Deserialize (System.IO.BinaryReader aReader)
		{
			JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte ();
			switch (type) {
				case JSONBinaryTag.Array:
					{
						int count = aReader.ReadInt32 ();
						JSONArray tmp = new JSONArray ();
						for (int i = 0; i < count; i++)
							tmp.Add (Deserialize (aReader));
						return tmp;
					}
				case JSONBinaryTag.Class:
					{
						int count = aReader.ReadInt32 ();                
						JSONClass tmp = new JSONClass ();
						for (int i = 0; i < count; i++) {
							string key = aReader.ReadString ();
							var val = Deserialize (aReader);
							tmp.Add (key, val);
						}
						return tmp;
					}
				case JSONBinaryTag.Value:
					{
						return new JSONData (aReader.ReadString ());
					}
				case JSONBinaryTag.IntValue:
					{
						return new JSONData (aReader.ReadInt32 ());
					}
				case JSONBinaryTag.DoubleValue:
					{
						return new JSONData (aReader.ReadDouble ());
					}
				case JSONBinaryTag.BoolValue:
					{
						return new JSONData (aReader.ReadBoolean ());
					}
				case JSONBinaryTag.FloatValue:
					{
						return new JSONData (aReader.ReadSingle ());
					}
 
				default:
					{
						throw new Exception ("Error deserializing JSON. Unknown tag: " + type);
					}
			}
		}
 
		#if USE_SharpZipLib
		public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
		{
			var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
			return LoadFromStream(zin);
		}
		public static JSONNode LoadFromCompressedFile(string aFileName)
		{
#if USE_FileIO
			using(var F = System.IO.File.OpenRead(aFileName))
			{
				return LoadFromCompressedStream(F);
			}
#else
			throw new Exception("Can't use File IO stuff in webplayer");
#endif
		}
		public static JSONNode LoadFromCompressedBase64(string aBase64)
		{
			var tmp = System.Convert.FromBase64String(aBase64);
			var stream = new System.IO.MemoryStream(tmp);
			stream.Position = 0;
			return LoadFromCompressedStream(stream);
		}
#else
		public static JSONNode LoadFromCompressedFile (string aFileName)
		{
			throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
		}
 
		public static JSONNode LoadFromCompressedStream (System.IO.Stream aData)
		{
			throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
		}
 
		public static JSONNode LoadFromCompressedBase64 (string aBase64)
		{
			throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
		}
		#endif
 
		public static JSONNode LoadFromStream (System.IO.Stream aData)
		{
			using (var R = new System.IO.BinaryReader (aData)) {
				return Deserialize (R);
			}
		}
 
		public static JSONNode LoadFromFile (string aFileName)
		{
			#if USE_FileIO
			using (var F = System.IO.File.OpenRead (aFileName)) {
				return LoadFromStream (F);
			}
			#else
			throw new Exception ("Can't use File IO stuff in webplayer");
			#endif
		}
 
		public static JSONNode LoadFromBase64 (string aBase64)
		{
			var tmp = System.Convert.FromBase64String (aBase64);
			var stream = new System.IO.MemoryStream (tmp);
			stream.Position = 0;
			return LoadFromStream (stream);
		}
	}
	// End of JSONNode
 
	public class JSONArray : JSONNode, IEnumerable
	{
		private List<JSONNode> m_List = new List<JSONNode> ();
 
		public override JSONNode this [int aIndex]
		{
			get {
				if (aIndex < 0 || aIndex >= m_List.Count)
					return new JSONLazyCreator (this);
				return m_List [aIndex];
			}
			set {
				if (aIndex < 0 || aIndex >= m_List.Count)
					m_List.Add (value);
				else
					m_List [aIndex] = value;
			}
		}
 
		public override JSONNode this [string aKey]
		{
			get{ return new JSONLazyCreator (this); }
			set{ m_List.Add (value); }
		}
 
		public override int Count
		{
			get { return m_List.Count; }
		}
 
		public override void Add (string aKey, JSONNode aItem)
		{
			m_List.Add (aItem);
		}
 
		public override JSONNode Remove (int aIndex)
		{
			if (aIndex < 0 || aIndex >= m_List.Count)
				return null;
			JSONNode tmp = m_List [aIndex];
			m_List.RemoveAt (aIndex);
			return tmp;
		}
 
		public override JSONNode Remove (JSONNode aNode)
		{
			m_List.Remove (aNode);
			return aNode;
		}
 
		public override IEnumerable<JSONNode> Children
		{
			get {
				foreach (JSONNode N in m_List)
					yield return N;
			}
		}
 
		public IEnumerator GetEnumerator ()
		{
			foreach (JSONNode N in m_List)
				yield return N;
		}
 
		public override string ToString ()
		{
			string result = "[ ";
			foreach (JSONNode N in m_List) {
				if (result.Length > 2)
					result += ", ";
				result += N.ToString ();
			}
			result += " ]";
			return result;
		}
 
		public override string ToString (string aPrefix)
		{
			string result = "[ ";
			foreach (JSONNode N in m_List) {
				if (result.Length > 3)
					result += ", ";
				result += "\n" + aPrefix + "   ";                
				result += N.ToString (aPrefix + "   ");
			}
			result += "\n" + aPrefix + "]";
			return result;
		}
 
		public override string ToJSON (int prefix)
		{
			string s = new string (' ', (prefix + 1) * 2);
			string ret = "[ ";
			foreach (JSONNode n in m_List) {
				if (ret.Length > 3)
					ret += ", ";
				ret += "\n" + s;
				ret += n.ToJSON (prefix + 1);
 
			}
			ret += "\n" + s + "]";
			return ret;
		}
 
		public override void Serialize (System.IO.BinaryWriter aWriter)
		{
			aWriter.Write ((byte)JSONBinaryTag.Array);
			aWriter.Write (m_List.Count);
			for (int i = 0; i < m_List.Count; i++) {
				m_List [i].Serialize (aWriter);
			}
		}
	}
	// End of JSONArray
 
	public class JSONClass : JSONNode, IEnumerable
	{
		private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode> ();
 
		public override JSONNode this [string aKey]
		{
			get {
				if (m_Dict.ContainsKey (aKey))
					return m_Dict [aKey];
				else
					return new JSONLazyCreator (this, aKey);
			}
			set {
				if (m_Dict.ContainsKey (aKey))
					m_Dict [aKey] = value;
				else
					m_Dict.Add (aKey, value);
			}
		}
 
		public override JSONNode this [int aIndex]
		{
			get {
				if (aIndex < 0 || aIndex >= m_Dict.Count)
					return null;
				return m_Dict.ElementAt (aIndex).Value;
			}
			set {
				if (aIndex < 0 || aIndex >= m_Dict.Count)
					return;
				string key = m_Dict.ElementAt (aIndex).Key;
				m_Dict [key] = value;
			}
		}
 
		public override int Count
		{
			get { return m_Dict.Count; }
		}
 
 
		public override void Add (string aKey, JSONNode aItem)
		{
			if (!string.IsNullOrEmpty (aKey)) {
				if (m_Dict.ContainsKey (aKey))
					m_Dict [aKey] = aItem;
				else
					m_Dict.Add (aKey, aItem);
			} else
				m_Dict.Add (Guid.NewGuid ().ToString (), aItem);
		}
 
		public override JSONNode Remove (string aKey)
		{
			if (!m_Dict.ContainsKey (aKey))
				return null;
			JSONNode tmp = m_Dict [aKey];
			m_Dict.Remove (aKey);
			return tmp;        
		}
 
		public override JSONNode Remove (int aIndex)
		{
			if (aIndex < 0 || aIndex >= m_Dict.Count)
				return null;
			var item = m_Dict.ElementAt (aIndex);
			m_Dict.Remove (item.Key);
			return item.Value;
		}
 
		public override JSONNode Remove (JSONNode aNode)
		{
			try {
				var item = m_Dict.Where (k => k.Value == aNode).First ();
				m_Dict.Remove (item.Key);
				return aNode;
			} catch {
				return null;
			}
		}
 
		public override IEnumerable<JSONNode> Children
		{
			get {
				foreach (KeyValuePair<string,JSONNode> N in m_Dict)
					yield return N.Value;
			}
		}
 
		public IEnumerator GetEnumerator ()
		{
			foreach (KeyValuePair<string, JSONNode> N in m_Dict)
				yield return N;
		}
 
		public override string ToString ()
		{
			string result = "{";
			foreach (KeyValuePair<string, JSONNode> N in m_Dict) {
				if (result.Length > 2)
					result += ", ";
				result += "\"" + Escape (N.Key) + "\":" + N.Value.ToString ();
			}
			result += "}";
			return result;
		}
 
		public override string ToString (string aPrefix)
		{
			string result = "{ ";
			foreach (KeyValuePair<string, JSONNode> N in m_Dict) {
				if (result.Length > 3)
					result += ", ";
				result += "\n" + aPrefix + "   ";
				result += "\"" + Escape (N.Key) + "\" : " + N.Value.ToString (aPrefix + "   ");
			}
			result += "\n" + aPrefix + "}";
			return result;
		}
 
		public override string ToJSON (int prefix)
		{
			string s = new string (' ', (prefix + 1) * 2);
			string ret = "{ ";
			foreach (KeyValuePair<string,JSONNode> n in m_Dict) {
				if (ret.Length > 3)
					ret += ", ";
				ret += "\n" + s;
				ret += string.Format ("\"{0}\": {1}", n.Key, n.Value.ToJSON (prefix + 1));
			}
			ret += "\n" + s + "}";
			return ret;
		}
 
		public override void Serialize (System.IO.BinaryWriter aWriter)
		{
			aWriter.Write ((byte)JSONBinaryTag.Class);
			aWriter.Write (m_Dict.Count);
			foreach (string K in m_Dict.Keys) {
				aWriter.Write (K);
				m_Dict [K].Serialize (aWriter);
			}
		}
	}
	// End of JSONClass
 
	public class JSONData : JSONNode
	{
		private string m_Data;
 
 
		public override string Value
		{
			get { return m_Data; }
			set {
				m_Data = value;
				Tag = JSONBinaryTag.Value;
			}
		}
 
		public JSONData (string aData)
		{
			m_Data = aData;
			Tag = JSONBinaryTag.Value;
		}
 
		public JSONData (float aData)
		{
			AsFloat = aData;
		}
 
		public JSONData (double aData)
		{
			AsDouble = aData;
		}
 
		public JSONData (bool aData)
		{
			AsBool = aData;
		}
 
		public JSONData (int aData)
		{
			AsInt = aData;
		}
 
		public override string ToString ()
		{
			return "\"" + Escape (m_Data) + "\"";
		}
 
		public override string ToString (string aPrefix)
		{
			return "\"" + Escape (m_Data) + "\"";
		}
 
		public override string ToJSON (int prefix)
		{
			switch (Tag) {
				case JSONBinaryTag.DoubleValue:
				case JSONBinaryTag.FloatValue:
				case JSONBinaryTag.IntValue:
					return m_Data;
				case JSONBinaryTag.Value:
					return string.Format ("\"{0}\"", Escape (m_Data));
				default:
					throw new NotSupportedException ("This shouldn't be here: " + Tag.ToString ());
			}
		}
 
		public override void Serialize (System.IO.BinaryWriter aWriter)
		{
			var tmp = new JSONData ("");
 
			tmp.AsInt = AsInt;
			if (tmp.m_Data == this.m_Data) {
				aWriter.Write ((byte)JSONBinaryTag.IntValue);
				aWriter.Write (AsInt);
				return;
			}
			tmp.AsFloat = AsFloat;
			if (tmp.m_Data == this.m_Data) {
				aWriter.Write ((byte)JSONBinaryTag.FloatValue);
				aWriter.Write (AsFloat);
				return;
			}
			tmp.AsDouble = AsDouble;
			if (tmp.m_Data == this.m_Data) {
				aWriter.Write ((byte)JSONBinaryTag.DoubleValue);
				aWriter.Write (AsDouble);
				return;
			}
 
			tmp.AsBool = AsBool;
			if (tmp.m_Data == this.m_Data) {
				aWriter.Write ((byte)JSONBinaryTag.BoolValue);
				aWriter.Write (AsBool);
				return;
			}
			aWriter.Write ((byte)JSONBinaryTag.Value);
			aWriter.Write (m_Data);
		}
	}
	// End of JSONData
 
	internal class JSONLazyCreator : JSONNode
	{
		private JSONNode m_Node = null;
		private string m_Key = null;
 
		public JSONLazyCreator (JSONNode aNode)
		{
			m_Node = aNode;
			m_Key = null;
		}
 
		public JSONLazyCreator (JSONNode aNode, string aKey)
		{
			m_Node = aNode;
			m_Key = aKey;
		}
 
		private void Set (JSONNode aVal)
		{
			if (m_Key == null) {
				m_Node.Add (aVal);
			} else {
				m_Node.Add (m_Key, aVal);
			}
			m_Node = null; // Be GC friendly.
		}
 
		public override JSONNode this [int aIndex]
		{
			get {
				return new JSONLazyCreator (this);
			}
			set {
				var tmp = new JSONArray ();
				tmp.Add (value);
				Set (tmp);
			}
		}
 
		public override JSONNode this [string aKey]
		{
			get {
				return new JSONLazyCreator (this, aKey);
			}
			set {
				var tmp = new JSONClass ();
				tmp.Add (aKey, value);
				Set (tmp);
			}
		}
 
		public override void Add (JSONNode aItem)
		{
			var tmp = new JSONArray ();
			tmp.Add (aItem);
			Set (tmp);
		}
 
		public override void Add (string aKey, JSONNode aItem)
		{
			var tmp = new JSONClass ();
			tmp.Add (aKey, aItem);
			Set (tmp);
		}
 
		public static bool operator == (JSONLazyCreator a, object b)
		{
			if (b == null)
				return true;
			return System.Object.ReferenceEquals (a, b);
		}
 
		public static bool operator != (JSONLazyCreator a, object b)
		{
			return !(a == b);
		}
 
		public override bool Equals (object obj)
		{
			if (obj == null)
				return true;
			return System.Object.ReferenceEquals (this, obj);
		}
 
		public override int GetHashCode ()
		{
			return base.GetHashCode ();
		}
 
		public override string ToString ()
		{
			return "";
		}
 
		public override string ToString (string aPrefix)
		{
			return "";
		}
 
		public override string ToJSON (int prefix)
		{
			return "";
		}
 
		public override int AsInt
		{
			get {
				JSONData tmp = new JSONData (0);
				Set (tmp);
				return 0;
			}
			set {
				JSONData tmp = new JSONData (value);
				Set (tmp);
			}
		}
 
		public override float AsFloat
		{
			get {
				JSONData tmp = new JSONData (0.0f);
				Set (tmp);
				return 0.0f;
			}
			set {
				JSONData tmp = new JSONData (value);
				Set (tmp);
			}
		}
 
		public override double AsDouble
		{
			get {
				JSONData tmp = new JSONData (0.0);
				Set (tmp);
				return 0.0;
			}
			set {
				JSONData tmp = new JSONData (value);
				Set (tmp);
			}
		}
 
		public override bool AsBool
		{
			get {
				JSONData tmp = new JSONData (false);
				Set (tmp);
				return false;
			}
			set {
				JSONData tmp = new JSONData (value);
				Set (tmp);
			}
		}
 
		public override JSONArray AsArray
		{
			get {
				JSONArray tmp = new JSONArray ();
				Set (tmp);
				return tmp;
			}
		}
 
		public override JSONClass AsObject
		{
			get {
				JSONClass tmp = new JSONClass ();
				Set (tmp);
				return tmp;
			}
		}
	}
	// End of JSONLazyCreator
 
	public static class JSON
	{
		public static JSONNode Parse (string aJSON)
		{
			return JSONNode.Parse (aJSON);
		}
	}
}


[출처] http://wiki.unity3d.com/index.php/SimpleJSON#Examples_.28C.23_.2F_UnityScript.29

반응형
Posted by blueasa
, |

I've come across the situation on a number of occasions when coding where I've wanted to convert from a string to an enum. In the Media Catalog sample, I resorted to one giant switch statement that has a case block for each string that returns an enum from it.

One of my colleagues came up with the answer yesterday; it's one of those methods that you can never find when you're looking for it, but once discovered it seems blindingly obvious:

   object Enum.Parse(System.Type enumType, string value, bool ignoreCase);

So you can write the following kind of code:

   enum Colour
   {
      Red,
      Green,
      Blue
   } 

   // ...
   Colour c = (Colour) Enum.Parse(typeof(Colour), "Red", true);
   Console.WriteLine("Colour Value: {0}", c.ToString());

   // Picking an invalid colour throws an ArgumentException. To
   // avoid this, call Enum.IsDefined() first, as follows:
   string nonColour = "Polkadot";

   if (Enum.IsDefined(typeof(Colour), nonColour))
      c = (Colour) Enum.Parse(typeof(Colour), nonColour, true);
   else
      MessageBox.Show("Uh oh!");

What a time saver - thanks, Simon!

Footnote: interestingly, whilst writing this up I noticed that Enum.IsDefined() doesn’t offer the ignoreCase parameter. If you don’t know whether the casing is right, it seems the only way to do the conversion is using the Parse method and catching the ArgumentException. That's not ideal, since it runs a lot slower. I wonder if this is a loophole in the design; no doubt someone like Brad could cast light on it...

posted on Friday, April 02, 2004 1:49 PM

Feedback

# re: How do you convert a string into an enum? 4/2/2004 7:22 PM SBC

You can get the string values of enums also by calling Enum.GetNames or Enum.GetName...




출처 : http://redccoma.tistory.com/117

반응형
Posted by blueasa
, |


출처: http://all4museum.tistory.com/entry/%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C-%ED%95%B8%EB%93%9C%ED%8F%B0-%EC%A0%95%EB%B3%B4-%EA%B0%80%EC%A0%B8%EC%98%A4%EA%B8%B0



기본정보, 맥주소, 번호 가져오기


1.android.os.Build 클래스에서 기본정보 받아오기

http://developer.android.com/reference/android/os/Build.html

먼저 Manifest 을 열어서 다음 퍼미션을 추가하여 폰의 정보를 읽을 수 있도록 합니다.

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

그러면 android.os 패키지의 Build 클래스를 통해서 구할 수 있습니다.
Build 클래스 안에 static 변수로 선언되어 있으므로 그 값을 직접 받아오면 됩니다.

SDK 2.1 에서는 아래의 정보를 제공합니다.

Build.BOARD
Build.BRAND
Build.CPU_ABI
Build.DEVICE
Build.DISPLAY
Build.FINGERPRINT
Build.HOST
Build.ID
Build.MANUFACTURER  -> 제조사
Build.MODEL               -> 모델명 
Build.PRODUCT
Build.TAGS
Build.TYPE
Build.USER

제게는 제조사와 모델명이 가장 중요한 정보였습니다.

Build.SERIAL 같은 정보는 SDK 2.3부터 지원한다고 하네요.




2. 맥주소 가져오기

맥주소는 와이파이 하드웨어 맥주소이므로 와이파이의 상태에 접근할 수 있는 퍼미션을 부여합니다.

먼저, Manifest 파일에 다음 퍼미션을 추가합니다.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

아래 코드로 값을 얻습니다.

WifiManager mng = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo info = mng.getConnectionInfo();
String mac = info.getMacAddress();





3. 폰번호 가져오기

폰의 정보를 읽어 올 수 있는 퍼미션을 부여합니다.

먼저, Manifest 파일에 다음 퍼미션을 추가합니다.
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

아래 코드로 값을 얻습니다.

TelephonyManager mng = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String num = mng.getLine1Number();



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



출처: http://batsu05.tistory.com/37






안드로이드 폰에서 Wi-Fi Mac 주소 가져오는 함수,
어떤 기계에서는 Wi-Fi 가 꺼져 있으면 못가져 온다고도 해서, 
Wi-Fi 가 활성화 되어있는지 체크하고 Mac 주소 가져옴.


  1. public String getCurrentMacAddress(){  
  2.     String macAddress="";  
  3.     boolean bIsWifiOff=false;  
  4.           
  5.     WifiManager wfManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);  
  6.     if(!wfManager.isWifiEnabled()){  
  7.         wfManager.setWifiEnabled(true);  
  8.         bIsWifiOff = true;  
  9.     }  
  10.           
  11.     WifiInfo wfInfo = wfManager.getConnectionInfo();  
  12.     macAddress = wfInfo.getMacAddress();  
  13.           
  14.     if(bIsWifiOff){  
  15.         wfManager.setWifiEnabled(false);  
  16.         bIsWifiOff = false;  
  17.     }  
  18.           
  19.     return macAddress;  
  20. }  




그리고 반드시 퍼미션을 지정해 줘야 함.

  1. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>  
  2. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>  
  3. <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>  
  4. <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>  
  5. <uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"/>  


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



출처: http://blog.naver.com/PostView.nhn?blogId=noeul_&logNo=140135587214


m_telephonyManager    =  (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        wfmanager     = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
        
        WifiInfo info    = wfmanager.getConnectionInfo();

 

        Log.i(TAG, " MDN 번호 "+m_telephonyManager.getLine1Number());
        Log.i(TAG, " IMEI "+m_telephonyManager.getDeviceId());
        Log.i(TAG, " MAC 주소 "+info.getMacAddress());
        Log.i(TAG, " 국가코드 "+m_telephonyManager.getNetworkCountryIso());
        Log.i(TAG, " 망 사업자 코드 MCC+MNC "+m_telephonyManager.getNetworkOperator());
        Log.i(TAG, " 망 사업자명 "+m_telephonyManager.getNetworkOperatorName());
        Log.i(TAG, " 가입자 ID "+m_telephonyManager.getSubscriberId());
        Log.i(TAG, " SIM카드 상태 "+m_telephonyManager.getSimState());

 

 

-퍼미션 설정 관련

 <uses-permission android:name="android.permission.INTERNET" /> 
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.READ_PHONE_STATE" />
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

 



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: http://javaexpert.tistory.com/193


퍼미션 관련 : 

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<uses-permission android:name = "android.permission.INTERNET"/>

<uses-permission android:name = "android.permission.READ_PHONE_STATE"/>


Mac 정보 및 전화번호 가져오기

public String getLocalPhoneNumber(){ //전화번호

     TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

     return manager.getLine1Number();

    }

public String getLocalIpAddress() {//맥 어드레스

        try {

            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {

                NetworkInterface intf = en.nextElement();

                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {

                    InetAddress inetAddress = enumIpAddr.nextElement();

                    if (!inetAddress.isLoopbackAddress()) {

                        return inetAddress.getHostAddress().toString();

                    }

                }

            }

        catch (SocketException ex) {

            ex.printStackTrace();

        }

        return null;

    }


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: http://blog.naver.com/PostView.nhn?blogId=ziippy&logNo=120138070384



안드로이드 디바이스의 IP 구하기  Android 


[출처] 안드로이드 디바이스의 IP 구하기|작성자 지피


존에 사용하던 IP 구하는 코드는, 이런 상황에서 3G IP 를 리턴해 준다. 그럼 대략 난감;;;

 

[기존 코드]

public String getLocalIpAddress()
 {
  try {
         for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
             NetworkInterface intf = en.nextElement();
             for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                 InetAddress inetAddress = enumIpAddr.nextElement();
                 if (!inetAddress.isLoopbackAddress()) {
                     return inetAddress.getHostAddress().toString();
                 }
             }
         }
     } catch (SocketException e) {
         Log.e(DEBUG_TAG, "getLocalIpAddress Exception:"+e.toString());
     }
     return null;
 }

 

그래서 WiFi IP 가 있으면 그걸 사용할 수 있게 조금 수정함

 

[수정 코드]

public String getLocalIpAddress()
 {
  final String IP_NONE = "N/A";
  final String WIFI_DEVICE_PREFIX = "eth";
  
  String LocalIP = IP_NONE;
  try {
         for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
             NetworkInterface intf = en.nextElement();           
             for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                 InetAddress inetAddress = enumIpAddr.nextElement();
                 if (!inetAddress.isLoopbackAddress()) {
                  if( LocalIP.equals(IP_NONE) )
                     LocalIP = inetAddress.getHostAddress().toString();
                  else if( intf.getName().startsWith(WIFI_DEVICE_PREFIX) )
                     LocalIP = inetAddress.getHostAddress().toString();
                 }
             }
         }
     } catch (SocketException e) {
         Log.e(DEBUG_TAG, "getLocalIpAddress Exception:"+e.toString());
     }
     return LocalIP;
 }

 

확인 결과 WiFi 장치에 대해 getName() 을 해 보니 "eth0" 을 얻을 수 있었음.

그러므로 "eth" 로 시작하는 장치가 있는 경우 해당 IP 를 LocalIP 라고 판단함.

 

갤럭시S, 디자이어 에서는 테스트가 잘 되었는데.. 글쎄 다른 단말에서도 잘 될런지는 ㅎㅎㅎ

 

여하튼, 이렇게 수정해서 사용하니

위와 같은 상황에서도 WiFi IP 를 가지고 통신이 잘 된다는 ㅋ

 




//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



Android Device의 IP 주소 가져오기


안드로이드에서 사용자의 단말이 WiFi에 고정 IP로 접속 했을 경우,

가끔 IP주소를 가져와서 작업해야할 경우가 생긴다.

이럴 경우 다음의 소스를 사용하면 된다.












물론 코드에서 필요로 하는 것들은 import해야 한다. 





01.public String getLocalIpAddress() {
02.try {
03.for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
04.{
05.NetworkInterface intf = (NetworkInterface) en.nextElement();
06.for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
07.{
08.InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
09.if (!inetAddress.isLoopbackAddress())
10.{
11.return inetAddress.getHostAddress().toString();
12.}
13.}
14.}
15.} catch (SocketException exception)
16.{
17.Log.e("We got Exception here", exception.toString());
18.}
19.return null;
20.}




//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


출처: http://dark2pee.tistory.com/entry/Android-IP-Address-%EA%B0%80%EC%A0%B8%EC%98%A4%EB%8A%94-%EC%86%8C%EC%8A%A4-%EC%98%88%EC%A0%9C


[Android] IP Address 가져오는 소스 예제


package exercice1.identificateur.ex;
 
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
 
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import exercice1.identificateur.R;
 
public class wifi1 extends ListActivity {
private static final String LOG_TAG = null;
public String getLocalIpAddress() {
    try {
        for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}
 
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
      tv.setText(getLocalIpAddress());
      setContentView(tv);  
}
}

//조금 수정

public String getLocalIpAddress()
{
    try {
        for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = (NetworkInterface)en.nextElement();
            for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = (InetAddress)enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}



출처 : http://202psj.tistory.com/588

반응형

'Programming' 카테고리의 다른 글

[링크] 예제로 배우는 GO 프로그래밍  (0) 2018.05.21
[펌] [iOS] info.plist Key 목록과 사용.  (0) 2018.03.26
Breakpad Client Libraries  (0) 2015.02.26
Posted by blueasa
, |

정규식을 이용하여 특정 문자만 얻는 방법을 알아보겠습니다.

 

- Namespace : System.Text.RegularExpressions

- Class : Regex

- Method : 

 

 public static string Replace(
string input,
string pattern,
string replacement
 )

 

 

1. 숫자만 얻기

 - 정규식 : [^0-9]

1
2
3
4
5
6
string str = "Englsh@korea$101299**한글";
 
// 숫자만 0-9
str = Regex.Replace(str, @"[^0-9]""");
 
// 결과 : 101299
cs

2. 영문자만 얻기

 - 정규식 : [^a-zA-Z]

1
2
3
4
5
6
string str = "Englsh@korea$101299**한글";
 
// 영문자 a-z A-Z
str = Regex.Replace(str, @"[^a-zA-Z]""");
 
// 결과 : Englshkorea
cs

 

3. 한글만 얻기

 - 정규식 : [^가-힣]

1
2
3
4
5
6
string str = "Englsh@korea$101299**한글";
 
// 한글만 가-힣
str = Regex.Replace(str, @"[^가-힣]""");
 
// 결과 : 한글
cs

 

4. 특수문자 제거

  - 정규식 : [^0-9a-zA-Z가-힣]

1
2
3
4
5
string str = "Englsh@korea$101299**한글";
// 특수문자 제거
str = Regex.Replace(str, @"[^0-9a-zA-Z가-힣]""");
 
// 결과 : Englshkorea101299한글
cs

 

※ 위의 예에서와 같이 정규식을 잘 이용하면 얻고자 하는 문자를 쉽게 처리 할 수 있습니다.

 

 

[출처]

http://docko.tistory.com/entry/C-%EC%A0%95%EA%B7%9C%EC%8B%9D%EC%9D%84-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EB%AC%B8%EC%9E%90-%EB%B3%80%ED%99%98

반응형
Posted by blueasa
, |
using System.Text.RegularExpressions;

bool IsValidStr(string text)
{
    string pattern = @"^[a-zA-Z0-9가-힣]*$";
    return Regex.IsMatch(text, pattern);
}

 

텍스트의 문자열이 대소문자, 알파벳, 숫자, 한글인지 체크하는 정규식이다.

특수 문자를 사용할수 없게 한다.


참고 할만한 곳 : http://highplus.org/app/header/js/fun_form_check.js@cacheBreak=

 
 

출처 : http://tenuakan.tistory.com/108

 

 
반응형
Posted by blueasa
, |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Diagnostics;
  
Stopwatch SW = new Stopwatch();
string sTemp1, sTemp2;
 
SW.Reset();
SW.Start();
 
// " 측정할 부분 작성 "
SW.Stop();
 
// 현재 인스턴스가 측정한 총 경과 시간을 가져옵니다.
sTemp1 = SW.Elapsed.ToString();                             // EX) "00:00:00.0000045"
// 현재 인스턴스가 측정한 밀리초 단위의 총 경과 시간을 가져옵니다
sTemp2 = SW.ElapsedMilliseconds.ToString() ;          // EX) "44"


출처 : http://overit.tistory.com/entry/C-%EC%8B%9C%EA%B0%84%EC%B2%B4%ED%81%ACStopwatch

반응형
Posted by blueasa
, |


링크 : http://www.qt-dev.com/

반응형
Posted by blueasa
, |